If you have a custom module and you want to programmatically create a custom content type in Drupal 7, follow the steps below.
1. Implement hook_node_info()
Define your new content type by implementing hook_node_info()
.
/** * Implements hook_node_info(). */ function mymodule_node_info() { return array( 'my_new_type' => array( 'name' => t('My New Type'), 'base' => 'my_new_type', 'description' => t('A sample description describing my new content type.') ) ); }
2. Implement hook_form()
In order for your new content type to appear in Admin > Structure > Content Types, a form must be defined for the new content type.
/** * Implements hook_form(). */ function mymodule_form($node, &$form_state) { $type = node_type_get_type($node); $form['title'] = array( '#type' => 'textfield', '#title' => check_plain($type->title_label), '#default_value' => !empty($node->title) ? $node->title : '', '#required' => TRUE, '#weight' => -5, ); return $form; }
It is enough to just define the form element for the title, as Drupal will automatically render the form elements for the rest of your fields attached to your custom content type. If you wish to change the way Drupal renders your form elements, you can override the defaults by defining your form elements here.
3. Implement hook_install()
A call to node_types_rebuild() ensures that your content type will appear when your module is enabled in case Drupal is caching the content types.
/** * Implements hook_install(). */ function mymodule_install() { node_types_rebuild(); }
That’s it! You can now create nodes with your new custom content type.