Tutorials

Customize our premium WordPress themes and stand out from the crowd.

Adding Custom Post Types to WordPress Theme

http://colorlabs.co/1iT7E7M

WordPress has default content types. At the first time you installed WordPress, you will get two content types by default: Post and Page. Most users use Posts for blog posts and Pages for static content. The fundamental difference between the two is that Pages aren’t time-specific, unlike Posts which are usually archived according to dates, months and years.

Sometime we need to publish something with specific content. For example, posting the products what we have for sale, share our portfolio, or make a list for all of our project. But we can’t use Posts and Pages to make that’s happen. We need to keep each type of content separated. So we need to create own type of the content. With Custom Post Types, we can create a new type  of items such as Posts and Pages which  will contain a different set of data. We will have a new management menu, custom taxonomies, custom meta boxes, and many more utilities that is required for full fledged publishing.

What are Custom Post Types and Taxonomies for WordPress?

Custom post types makes you allow to display and categorize different types of content outsides of the 5 native WordPress content types (i.e. Post, Page, Attachment, and so forth). The addition of this feature is a big step forward in the making of WordPress a full-fledged CMS, beside its normal use as a blogging platform. To categorize custom post types you can use taxonomies. Taxonomies is a great way to group things together and help us to search posts belonging to a specific group. In WordPress, we generally use Categories and Tags as taxonomies.

In this tutorial, i will tell you on how to use your own custom post type. More specifically, we will create a “Portfolio” post type. Lets get started.

First, let’s register the post type in functions.php. This is the code:

add_action( 'init', 'create_portfolio_post_type' );

function create_portfolio_post_type() {
    $args = array(
                  'description' => 'Portfolio Post Type',
                  'show_ui' => true,
                  'menu_position' => 4,
                  'exclude_from_search' => true,
                  'labels' => array(
                                    'name'=> 'Portfolios',
                                    'singular_name' => 'Portfolios',
                                    'add_new' => 'Add New Portfolio',
                                    'add_new_item' => 'Add New Portfolio',
                                    'edit' => 'Edit Portfolios',
                                    'edit_item' => 'Edit Portfolio',
                                    'new-item' => 'New Portfolio',
                                    'view' => 'View Portfolios',
                                    'view_item' => 'View Portfolio',
                                    'search_items' => 'Search Portfolios',
                                    'not_found' => 'No Portfolios Found',
                                    'not_found_in_trash' => 'No Portfolios Found in Trash',
                                    'parent' => 'Parent Portfolio'
                                   ),
                 'public' => true,
                 'capability_type' => 'post',
                 'hierarchical' => false,
                 'rewrite' => true,
                 'supports' => array('title', 'editor', 'thumbnail', 'comments')
                 );
    register_post_type( 'portfolio' , $args );
}

This the screenshot to register the portfolio

Register Post Type

The next step is to register portfolio_category for the portfolio taxonomy and here is the code :

/*====================================================
Register Custom Taxonomies
======================================================*/

add_action('init', 'register_portfolio_taxonomy');

function register_portfolio_taxonomy() {
  register_taxonomy('portfolio_category',
                    'portfolio',
                     array (
                           'labels' => array (
                                              'name' => 'Portfolio Categories',
                                              'singular_name' => 'Portfolio Categories',
                                              'search_items' => 'Search Portfolio Categories',
                                              'popular_items' => 'Popular Portfolio Categories',
                                              'all_items' => 'All Portfolio Categories',
                                              'parent_item' => 'Parent Portfolio Category',
                                              'parent_item_colon' => 'Parent Portfolio Category:',
                                              'edit_item' => 'Edit Portfolio Category',
                                              'update_item' => 'Update Portfolio Category',
                                              'add_new_item' => 'Add New Portfolio Category',
                                              'new_item_name' => 'New Portfolio Category',
                                            ),
                            'hierarchical' =>true,
                            'show_ui' => true,
                            'show_tagcloud' => true,
                            'rewrite' => false,
                            'public'=>true
                            )
                     );
}

This is the screenshot to register the portfolio categories

Register Taxonomy

And now we have already finished registering the custom post type with the custom taxonomy. And for the next step we need to custom the column of portfolio list and add some filter by the taxonomy. here is the code to custom the columns of portfolio list:

add_filter("manage_edit-portfolio_columns", "portfolio_edit_columns");

function portfolio_edit_columns($columns){
   $columns = array(
                    "cb" => "<input type='checkbox' />",
                    "photo" => __("Image"),
                    "title" => __("Portfolio"),
                    "portfolio_category" => __("Portfolio Category"),
                    "date" => __("Date")
                   );

   return $columns;
}

add_action("manage_portfolio_posts_custom_column",  "portfolio_custom_columns");

function portfolio_custom_columns($column){
  global $post;
  switch ($column){
                 case "photo":
                     if(has_post_thumbnail()) the_post_thumbnail(array(50,50));
                 break;
                 case "portfolio_category":
                     echo get_the_term_list($post->ID, 'portfolio_category', '', ', ','');
                 break;
   }
}

And then this code for filtering by portfolio category:


if ( isset($_GET['post_type']) ) {
   $post_type = $_GET['post_type'];
}else {
   $post_type = '';
}

if ( $post_type == 'portfolio' ) {
   add_action( 'restrict_manage_posts','portfolio_filter_list' );
   add_filter( 'parse_query','perform_filtering' );
}

function portfolio_filter_list() {
   global $typenow, $wp_query;
   if ($typenow=='portfolio') {
      wp_dropdown_categories(array(
                                   'show_option_all' => 'Show All Portfolio Category',
                                   'taxonomy' => 'portfolio_category',
                                   'name' => 'portfolio_category',
                                   'orderby' => 'name',
                                   'selected' =>( isset( $wp_query->query['portfolio_category'] ) ? $wp_query->query['portfolio_category'] : '' ),
                                   'hierarchical' => false,
                                   'depth' => 3,
                                   'show_count' => false,
                                   'hide_empty' => true,
                            ));

   }
}

function perform_filtering( $query ){
   $qv = &$query->query_vars;
   if (( $qv['portfolio_category'] ) && is_numeric( $qv['portfolio_category'] ) ) {
      $term = get_term_by( 'id', $qv['portfolio_category'], 'portfolio_category' );
      $qv['portfolio_category'] = $term->slug;
   }
}

You will see the portfolio list at your dashboard. And all those codes above will give you this screenshot as a result.

Add Filter to List

There are easiest and the fastest way to create custom and high quality code for your WordPress project using the latest WordPress coding standards and API’s then your code manual like the above, you can generate the function automatically with GenerateWP. Click this link to try generate some function.

I hope you will be able to grasp the significance of Custom Post Types. There is more to explore, just play around with it. Good luck! If you have any further questions or have suggestion, feel free to leave the comment bellow.

  • jradar

    hi, i’m trying to replicate this tutorial on my site, but i’m not seeing anything showing up in the admin … i’m using WP 3.8.1 and a twentytwelve child theme

    any ideas on what is going on?

    • jradar

      i got it to work, i had to change this line:

      “cb” => “”,
      to this
      “cb” => “”,

      so single quotes were used around this part ‘"checkbox"’

      thanks very much for the tutorial

      • Anang

        Great! :)

        • Hemu

          Hi i am newbie in WP

          where can i put all above code i mean in which file plz plz tell me

          • Anang

            Hi Hemu,

            You can put all code to your functions.php of your theme

  • jradar

    now i’m getting this error:

    Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘portfolio_type_filter_list’ not found or invalid function name in /home/sunlab2/public_html/wp-includes/plugin.php on line 429

    • jradar

      any ideas?

  • jradar

    also, how does one get the portfolio project to show up on the front end??

    • Anang

      To make it, you can put these codes into your index.php.

      $args = array(
      ‘post_type’ => ‘portfolio’,
      );
      $the_query = new WP_Query( $args );

      // The Loop
      if ( $the_query->have_posts() ) {
      echo ”;
      while ( $the_query->have_posts() ) {
      $the_query->the_post();
      echo ” . get_the_title() . ”;
      }
      echo ”;
      } else {
      // no posts found
      }

  • james

    $columns = array(
    “cb” => “”,
    “photo” => __(“Image”),
    “title” => __(“Portfolio”),
    “portfolio_category” => __(“Portfolio Category”),
    “date” => __(“Date”)
    );

    ERROR

    • mahesh

      “”

      • mahesh

        “”

    • Anang

      Please try again, I’ve already updated the tutorial. I hope, it can help you. :)

  • http://www.com/ Net-Vie

    delete the ‘type’ word and it will work,

    portfolio_type_filter_list() —-> portfolio_filter_list()

    • Anang

      Hi Net-Vie

      Thanks for your revision. :)

      • Hemu

        Hello how can i get the content

        • Anang

          You can put this code into your index.php or some file as you want

          $args = array(
          ‘post_type’ => ‘portfolio’,
          );
          $the_query = new WP_Query( $args );

          // The Loop
          if ( $the_query->have_posts() ) {
          echo ”;
          while ( $the_query->have_posts() ) {
          $the_query->the_post();
          echo ” . get_the_title() . ”;
          }
          echo ”;
          } else {
          // no posts found
          }

  • Marty

    Great tutorial! Wondering about best practice to display posts on page by custom category?

    • Anang

      Thank you Marty,

      To make that happen, you can use WP_Query and make some queries.

  • pdv

    how do i display them, tried different chunks of code, none works

    • Anang

      Hi,

      Please try again, I’ve already updated the tutorial. I hope, it can help you. :)

  • http://www.webexplorar.com/ Sumith Harshan

    Hi,
    Thanks for the great tutorial. How can I add custom tags for this portfolio custom post type?

    Thanks again.

  • asdf

    this is not really a tutorial cause it doesnt explain anything..

    • http://colorlabsproject.com/ ColorLabs & Company

      Hi, we’re sorry that you don’t find it useful. However, thank you for your feedback. Perhaps you can send us your questions here and we’ll try to explain it for you. Thanks!

  • Girish Tiwari

    Great, really appreciate your efforts , i am looking for a custom post with type/category from a long time.
    Thanks

  • Girish Tiwari

    How can i get portfolio for a specific category in frontend?

  • Marty

    Great tutorial! I’ve used this on few projects without problems. Up until now :) For some reason I get an Notice: Undefined index: portfolio_category in /Applications/MAMP/htdocs/… It seems this line is causing the problem: if (( $qv['portfolio_category'] ) && is_numeric( $qv['portfolio_category'] ) ) Any idea on why?
    Thank’s!

    • Marty

      Found an answer to this: if (( isset($qv['portfolio_category'] )) && is_numeric( $qv['portfolio_category'] ) ). That is I’m making sure that $qv['portfolio_category'] is set. Gets rid of the undefined index warning…