Custom Post Types

WordPress provides methods of creating new custom post type. By default wordpress comes with different sets of post types, these are:

  • Posts
  • Pages
  • Attachments
  • Navigation Menus Items
  • Revisions
  • Links (if you’re using the blogroll feature)

Ways to creating post types

You can use ready made plugins to create custom post type like https://wordpress.org/plugins/custom-post-type-ui/ which easiest way to create custom post type. Download the plugin and activate the plugin, and follow the instruction to create the custom post type. The Custom Post Type UI plugin also allows you to create custom taxonomies.

Manual creation of post type:

You can create custom post type as an plugin which is best practice to create custom post type or you can simply use your theme to create cusomt post type for you. Here, I am talking about custom post in theme function.php file.

Step 1: Register Post type

Open your theme function.php file and add the code below it with PHP tags.

function custom_post_product() {
    $labels = array(
        'name'               => _x( 'Products', 'post type general name' ),
        'singular_name'      => _x( 'Product', 'post type singular name' ),
        'add_new'            => _x( 'Add New', 'product' ),
        'add_new_item'       => __( 'Add New Product' ),
        'edit_item'          => __( 'Edit Product' ),
        'new_item'           => __( 'New Product' ),
        'all_items'          => __( 'All Products' ),
        'view_item'          => __( 'View Product' ),
        'search_items'       => __( 'Search Products' ),
        'not_found'          => __( 'No products found' ),
        'not_found_in_trash' => __( 'No products found in the Trash' ),
        'parent_item_colon'  => '',
        'menu_name'          => 'Products'
      );
    $args = array(
        'labels'        => $labels,
        'description'   => 'Holds our products and product specific data',
        'public'        => true,
        'show_ui'        => true,
        'capability_type' => 'post',
        'hierarchical' => false,
        'rewrite' => array('slug' => 'products'),
        'query_var' => true,
        'menu_icon' => 'dashicons-video-alt',
        'menu_position' => 5,
        'supports' => array(
            'title',
            'editor',
            'excerpt',
            'trackbacks',
            'custom-fields',
            'comments',
            'revisions',
            'thumbnail',
            'author',
            'page-attributes',),
        'has_archive'   => true,
    );
    register_post_type('product', $args);
    //flush_rewrite_rules();
}
add_action('init', 'custom_post_product');

Code Definitions

  • function custom_post_product() – Here we create a new function for our custom post type. We do this to limit conflicts with any other code inside our functions.php file. It is also a best practice when adding new code to any file like functions.php.
  • label – A plural descriptive name for the post type marked for translation. If you don’t declare a custom label, WordPress will use the name of the custom post type by default.
  • public – Whether a post type is intended to be used publicly either via the admin interface or by front-end users. WordPress sets this to false by default.Here we set it to true as we do what our custom post type to display publicly.
  • show_ui – Generates a default UI for managing this post type in the admin. You can set this to true or false. For the sake of usability, a UI in the admin area is always a good thing.
  • capability_type – Here we can declare what type of custom post type we will be dealing with. It is used to build the read, edit, and delete capabilities of a post or page. You can choose either post or page.
  • hierarchical – Whether the post type is hierarchical(e.g. page). Or in laymen’s terms, whether or not you can declare a parent page, child page, etc… of the post type. This is mainly intended for Pages. Here we declare it false so there’s no need to worry about it for our example.
  • rewrite – This rule is either true or false. The default is true so if slug argument is entered then the slug name is prepended to the posts. Our slug “products” will be prepended to each new post of that type.
  • query_var – This rule is either true or false. It sets the post type name as a query variable.
  • menu_icon – This rule declares a custom icon for the admin area. Here we use a neat resource called dashicons that are included in WordPress already.
  • supports – This is usually an array of features the custom post type will support. Here we have quite a long list. These will tie into the admin area.
  • register_post_type($post_type, $args); – The register_post_type() is a function that WordPress recognizes as a custom post type generator. In this example it accepts two parameters which are the name of the post type itself and any arguments you would like to call.
  • add_action(‘init’, ‘custom_post_product’ ); – This line of code returns or calls our function so it fires and displays within our site.

If you are ever in doubt you can’t go wrong looking at the Official WordPress Codex for more information on custom post types.

Step 2 – Test

Now that we have defined our custom post type inside our functions.php file, head to your WordPress dashboard to see that we did everything correctly. You should now have a new menu item on the left side of your screen titled Products.

Step 3 – Displaying the post type on the front end

Once you’ve added some products, you’ll need to be able to display these on the front end of your site.

Setting Permalinks to Link to Your Post Type’s Pages

First you need to refresh the permalinks on your site so that WordPress will use the correct links to display products or product archives:

  1. In the WordPress admin, go to Settings -> Permalinks.
  2. Make sure the ‘post name’ option is selected.
  3. Click the Save Changes button.

Now that we have defined our custom post type inside our functions.php file, head to your WordPress dashboard to see that we did everything correctly. You should now have a new menu item on the left side of your screen titled Products.

Step 4: Adding Your Post Type to the Navigation Menu

If you want to add products to your navigation menu, you can. Go to Appearance -> Menus, and you’ll see that Products are displayed on the left. Simply drag any products onto your menu to include them.

Adding your product archive is a bit trickier, and for this you’ll need to add a custom link to the menu.

  1. Still on the Menus screen, click on the Links box to the left.
  2. In the URL field, type http://mysite.com/product/, replacing mysite.com with your own domain.
  3. In the Link text field, type Products.
  4. Click the Add to Menu button.
  5. Once the link has been added to the menu, move it to the right place and save the menu.
  6. Save your changes by clicking Save Menu. Don’t miss this step!

Step 5: A Template for your Post Type

WordPress uses something called the template hierarchy to identify which template file in your theme it should use to display a given content type. It’s beyond the scope of this post to describe how the template hierarchy works in detail, but it helps to know how WordPress displays your new post type.

When WordPress displays a single product, it will look for each of these files in order in your theme:

  1. A file for displaying single products, called single-product.php.
  2. A file for deploying all single posts of any post type, called single.php.
  3. The generic file for deploying all kinds of content, called index.php.

When WordPress displays a product archive, it will work through these template files:

  1. A file for displaying the product archive, called archive-product.php.
  2. A generic archive template, called archive.php.
  3. The default template, index.php.

WordPress will work through this hierarchy and use the template file it comes across first. So if you want to create a custom template for your products, a good place to start is by copying the single.php file, saving it as single-product.php and editing that.

However if you don’t want to create template files, WordPress will happily use the files already present in your theme, which is what it’s done for me with the twenty fifteen theme’s archive.php and single.php files.

Displaying Custom Post Types on The Front Page

One advantage of using custom post types is that it keeps your custom content types away from your regular posts. However, if you would like them to display among your regular post, then you can do so by adding this code into your theme’s functions.php file or a site-specific plugin:

add_action( 'pre_get_posts', 'add_custom_post_product_to_query' );

function add_custom_post_product_to_query( $query ) {
	if ( is_home() && $query->is_main_query() )
		$query->set( 'post_type', array( 'post', 'product' ) );
	return $query;
}

Querying Custom Post Types

If you are familiar with the coding and would like to run loop queries in your templates, then here is how to do that.

<?php 
   $args = array( 'post_type' => 'product', 'posts_per_page' => 10 );
   $the_query = new WP_Query( $args ); 
?>
<?php if ( $the_query->have_posts() ) : ?>
        <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <h2><?php the_title(); ?></h2>
        <div class="entry-content">
           <?php the_content(); ?> 
        </div>
        <?php wp_reset_postdata(); ?>
<?php else:  ?>
      <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>