How To Create New Content Type Programmatically in Drupal 7?

alsator picture alsator · Nov 14, 2011 · Viewed 15.6k times · Source

I'm building a module (my_module) in Drupal 7.

It has some functionality and also will create new content type.

In my_module.install I implemented the hook_install (my_module_install).

Can I use more one implementation of hook_install to create new content type (my_cck_install) in this module?

If (yes), how should I do this?

Else: have I do this in another module? :-)

Answer

Clive picture Clive · Nov 14, 2011

You can't use more than one implementation of hook_install in the same module; in PHP you can't have 2 function with the same name which rules this out.

You would just need to add your new content type in the same hook_install anyway (have a look at how the standard installation profile does it at /profiles/standard/standard.install). This is how I always add new content types from the install file (using the example of a testimonials module):

function testimonial_install() {
  // Make sure a testimonial content type doesn't already exist
  if (!in_array('testimonial', node_type_get_names())) {
    $type = array(
      'type' => 'testimonial',
      'name' => st('Testimonial'),
      'base' => 'node_content',
      'custom' => 1,
      'modified' => 1,
      'locked' => 0,
      'title_label' => 'Customer / Client Name'
    );

    $type = node_type_set_defaults($type);
    node_type_save($type);
    node_add_body_field($type);
  }
}