[DRUPAL 7] How to create a custom content type programmatically?

| | 2 min read

It is very easy to create a content type through admin section of Drupal. But have you tried doing it programmatically? This article will explain to you how to do this in a very simple way. Even though fields can also be added to the content type programmatically, this section only covers the creation of content type.

Let us pretend we have the following lists with us:

  1. A directory named "myModule".
  2. An info file, named "myModule.info".
  3. A module file called "myModule.module".
  4. An install file, myModule.install in the module folder.

If you have created all the required files as per the above lists, follow the below steps:

  • Step 1: Decide a display and machine name for our content type.
    For eg: Assume our content type's display name is 'Slideshow' and machine name is 'slideshow'.
  • Step 2: Implement hook_install() in your myModule.install file.
  • Step 3: Define the node type.
  • Step 4: Pass the node type to the function node_type_set_defaults(), which will set default values for the node.
  • Step 5: If you want to add "Body" field, to the content type, use the function node_add_body_field().
  • Step 6: Save the content type using node_type_save().

Below is the code which executes all the above steps.

<?php
/**
 * Implements hook_install().
 */
function myModule_install() { 
  $t = get_t(); // runs in both the installer and runtime

  /* Create and save a new content object */
  $slideshow = 'slideshow'; // machine name of the content type

  // define the node type
  $slideshow_images = array(
    'type' => $slideshow,
    'name' => $t('Slideshow'),// Display name of the content type
    'base' => 'node_content',
    'title_label' => $t('Title'),
    'description' => $t('To add images and captions.'),
    'custom' => TRUE,
  );

  // set other node defaults not declared above
  $content_type = node_type_set_defaults($slideshow_images);

  // add the body field
  node_add_body_field($content_type, $t('Body'));

  // save the content type
  node_type_save($content_type);
}
?>

After creating this, you will have 'Slideshow' as one of your content types in your 'admin/structure/content' page.