Create your first WordPress Custom Post Type

WordPress has been gaining a foothold in the general content management system (CMS) game for a few years now, but the real breakthrough was the custom post type mechanism which allows for the creation of a wide variety of content. Let’s take a look at how this came to be and all the options that this great functionality offers.

Step 1

Here’s the first bit of code we need to add to functions.php, which I’ll review below.


add_action( 'init', 'project_activate' );
function project_activate(){
$labels = array(
'name' => _x('Projects', 'project'),
'singular_name' => _x('Project Item', 'project'),
'add_new' => _x('Add New Project', 'project item'),
'add_new_item' => __('Add New Project Item'),
'edit_item' => __('Edit Project Item'),
'new_item' => __('New Project Item'),
'view_item' => __('View Project Item'),
'search_items' => __('Search Project'),
'not_found' => __('Nothing found'),
'not_found_in_trash' => __('Nothing found in Trash'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'query_var' => true,
'menu_icon' => plugins_url('/images/', __FILE__) . 'project.png',
//'rewrite' => true,
'rewrite' => array('slug'=>'projects'),
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','custom-fields','thumbnail','comments','author'),
'taxonomies'=>array('project-cat')
);
register_post_type( 'projects' , $args );

}

Anyone who’s worked with WordPress before will recognise the structure here. We’re adding an action when the WP Admin initialises to call the function project_activate(). In that function we create two arrays, $labels and $args, and then use register_post_type to pull it all together. In doing so we name the new custom post type ‘project’ and tell it to use the arguments from $args.

The devil is in the detail, so let’s run over some of those arguments. A full list can be found at http://codex.wordpress.org/Function_Reference/register_post_type. First let’s look at $labels:

  • name this is the (probably plural) name for our new post type
  • singular_name how you’d refer to this in the singular (such as ‘Add new ****’)

That’s the first simple step, and it should be enough to see your new custom post time in the WordPress admin. Save functions.php and take a look!

Step 2

Use below code to register taxonomy .


register_taxonomy_for_object_type('project_tag', 'projects');

function project_create_taxonomies()
{
// Project Categories
register_taxonomy(‘project-cat’,array(‘project’),array(
‘hierarchical’ => true,
‘label’ => ‘Project Categories’,
‘singular_name’ => ‘Project Category’,
‘show_ui’ => true,
‘query_var’ => true,
‘rewrite’ => array(‘slug’ => ‘project-cat’ )
));
}

 

Now Custom Post type has been successfully created in wordpress admin enjoy coding….

Leave a Comment

Your email address will not be published. Required fields are marked *