Create a node content type programmatically

If you’re a new Drupal user, you may have already created a fresh content type manually to organize your site correctly. But what happens if you want to create this content type with your module installation and don’t want to do it manually each type you install it on a new website ?. Here is how to create a content type programmatically with Drupal 7. 

Begin with a new array containing custom properties

Complete the content type definition by setting any defaults not explicitly declared above with node_type_set_defaults method.

 

We add a body field and set the body label immediately.

 

Save the content type

 

If you want to modify some body display settings, load the instance definition from the existing content type’s body with field_info_instance

 

Now you can modify the array settings, an example: Instructing the body to display as a summary

 

Save our changes to the body field instance. field_update_instance

 

The hardest part will be to define and add all fields and instances to the content type. If you have lots of fields, I would give advice to add them in a foreach loop like this:

You have to understand the difference between field_create_field and field_create_instance. The first will create a new table in the database and contains how the data is saved into db, the second will be based on an existing field linked to the content type and contains display settings.

So if you create new fields all the time instead of reusing existing ones, you’re going to have a big number of db tables automatically created by Drupal. Then you should try reusing whenever you can all existing fields to simply create links between the field and your new content type. You can use only one time a field for each content type.

 

Example of the two function implementations:

  • node_test_filter is a taxonomy based selection field
  • node_test_text is a textarea field

 

 

7 Thoughts on “Create a node content type programmatically

  1. drtimofey on November 15, 2014 at 09:07 said:

    FYI – The code should go into /mymodule/mymodule.install file, not into *.module.

  2. sunial on May 27, 2015 at 09:25 said:

    this code not working

  3. Your code missinga function _custom_filters_options_list

    • I don’t see the need here. Tell me ?

      • admin on April 21, 2017 at 13:48 said:

        For example if you need a content type to be created by a module on multiple drupal installation.
        You don’t want to create everywhere the same content type, even more if there are lots of fields to add.

Leave a Reply

Your email address will not be published.

Post Navigation