Despite the fact that WordPress rules the CMS arena, many people still consider WordPress nothing more than a blogging platform it was originally created for. Strictly speaking, over the last five years, WordPress has evolved into a much more sophisticated, flexible and robust publishing platform. With new exciting features such as custom post types, widgets, menus and post formats, WordPress has opened up a whole new world of possibilities for users.

In this tutorial, I’m going to explore Custom Post Types in WordPress. Firstly, I’ll make you familiar with custom post types and custom taxonomies, and then take you through creating a custom product post type. Additionally, I’ll also show how you can make the most of a custom post type.

Let’s get started!

What are Custom Post Types?

The term Post Type refers to a specific content type in a WordPress site. By default, WordPress comes with five different post types: post, page, revision, attachment and nav_menu_item. Of these five, post and page are two main content types used by most of the users for blog posts and static content respectively. Unlike pages, posts are time-specific and thus archived according to date, month or year. All the post types in WordPress take place in the database table called wp_posts and are differentiated by post_type, a column defined in the same table.

What if, sometime you need to publish a specific type of content beyond above mentioned native content types? That’s where Custom post types show their magic. Luckily, since the release of WordPress 3.0, you’re allowed to create your own custom post types, call them whatever you want and use them the way you like. For example, if you run a product based site, chances are you would like to create a product post type having different custom fields and its own custom taxonomies. In short, Custom post types are new post types that a user can create to store, display and categorize different types of content in WordPress.

A Little Bit about Custom Taxonomies

You might have noticed in above paragraph, I’ve used a word “custom taxonomies”. Let’s first understand what is taxonomy? In WordPress, taxonomy is a great way to group core post types or links or custom post types together. Like default post types, WordPress has four default taxonomies: category, post_tag, link_category, and post_format.

However, in some cases like a custom post type, you can go outside these four built-in taxonomies. WordPress allows you to create your own custom taxonomies and use them in a specific post type to organize and classify your content more efficiently. For instance if you have a movie review website, you can define year” as a taxonomy for movie post type, and then use it to group and sort your movies by year.

Creating a Custom Post Type

If you’re familiar to PHP and have a little bit knowledge of WordPress, creating your own custom post type would not be difficult for you. You can easily add a custom post type to WordPress using the register_post_type() function that takes two parameters: first, the name of the custom post type and second, arguments to be called for this post type. Take a look at the following code that you need to include in your theme’s functions.php file.

add_action( 'init', 'create_product_post_type' );
function create_product_post_type() {
        $args = array();
	register_post_type( 'product', $args);
}

This will create a ‘product’ post type without any customization. It would neither be public, nor would be displayed in the admin screen. To customize this newly created post type to fit your requirements, you need to add some most commonly used options to the empty $args array as I’ve done.

add_action( 'init', 'create_product_post_type' );
function create_product_post_type() {
	$args = array(
		'labels' => array(
				'name'               => _x( 'Products', 'post type general name' ),
				'singular_name'      => _x( 'Product', 'post type singular name' ),
				'menu_name'          => _x( 'Products', 'admin menu' ),
				'add_new'            => _x( 'Add New', 'product' ),
				'add_new_item'       => __( 'Add New Product' ),
				'new_item'           => __( 'New Product' ),
				'edit_item'          => __( 'Edit Product' ),
				'view_item'          => __( 'View Product' ),
				'all_items'          => __( 'All Products' ),
				'search_items'       => __( 'Search Products' ),
				'parent_item_colon'  => __( 'Parent Product:' ),
				'not_found'          => __( 'No products found.' ),
				'not_found_in_trash' => __( 'No products found in Trash.' )
 			),
		'description' => 'Product Post Type',
		'public'        => true,
		'query_var'          => true,
		'show_ui'            => true,
		'menu_position' => 5,
		'capability_type'    => 'post',
		'has_archive' => true,
		'hierarchical' => false,
		'exclude_from_search' => false,
		'supports'           => array( 'title', 'thumbnail', 'excerpt', 'comments' )
	);
		register_post_type( 'product', $args);
}

Let’s understand what’s going on in the above code.

labels :The labels option is an array that defines different labels associated with our product post type. If a custom label is not declared, WordPress will set ‘name’ to the value of ‘label’ by default.

description : A short explanation of what our custom post type is.

public :This option controls how the custom post type will be visible to authors and readers. By default, WordPress sets this to false. In my code, I’ve set it to true as I want to make the product custom post type visible to everyone.

A Boolean value to set the post type name as a query variable.

show_ui :A Boolean value to decide whether WordPress will generate a default user interface for managing the custom post type.

menu_position :This option will set the position of the custom post type menu in the WordPress back end. By default, a custom post type menu appears below Comments. By adjusting the value of menu_position, you can declare where the menu should be placed.

capability_type :This string is used to build the read, edit, and delete capabilities of a page or post.

has_archive :A Boolean value used to enable post type archives.

hierarchical :A Boolean value to decide if the post type is hierarchical. As I don’t want products to be hierarchical, therefore I’ve set it to false.

exclude_from_search : A Boolean value to decide whether or not WordPress should exclude posts associated with the custom post type from front end search results.

supports :An array of features supported by the custom post type.

To see what else could be done with custom post types, I suggest you to go through the arguments list in the WordPress Codex.

Once you’ve included the above code in your theme’s functions.php file, you’ll be able to see your new custom post type menu in the WordPress admin area.

How to Display a Custom Post Type on Your Site?

If the created custom post type has has_archive set to “true”, you can see your custom post list by going to http://yoursite.com/products. To display the custom post type on your website, use any one of following methods:

Using Default Archive Template

Just go to Appearance » Menus in your WordPress dashboard and add a custom link to your custom post type menu. Click the save button and visit your site. You’ll see a new menu has been added there. Click on it to see your custom post type archive page.

Using Custom Templates

In case, you’re not satisfied with the appearance of custom post type archive page, then you can make use of a custom template. All you have to do is to create a new file, named archive-products.php, in your theme directory. After that, copy all the contents of archive.php into archive-products.php file and customize it to fit your needs. In the same way, you can also create single-products.php template to display single entry of your custom post type. Just copy all the contents of single.php file into single-products.php file and modify it to fit your needs.

Remark :Don’t forget to replace http://yoursite.com with your own domain name and products with your own custom post type.

Displaying Posts of Custom Post Types on the Home Page

If you want to display your custom post type posts among standard post type, then you can do this by using the pre_get_posts action hook. Simply add the following code snippet to your theme’s functions.php file.

add_action( 'pre_get_posts', 'add_product_post_types_to_query' );
function add_product_post_types_to_query( $query ) {
	if ( is_home() && $query->is_main_query() )
		$query->set( 'post_type', array( 'post', 'products' ) );
	return $query;
}

Querying Custom Post Types

If you want to retrieve posts from your custom post type, you can do it via the post_type argument of the WP_Query class.

<?php 
$args = array( 'post_type' => 'products', 'posts_per_page' => 5 );
$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 items found.' ); ?></p>
<?php endif; ?>

The above code will simply loops through the 5 latest items of the product post type and displays their title and content one by one.

Author Bio :-

Ajeet is an experienced WordPress developer. Currently, he is working with WordPress Integration. In his spare time, he loves to write about HTML5, Responsive, WordPress, eCommerce, and JavaScript and share his work experience with others. For weekly updates, follow @Wordpress_INT.


This post is by a guest author, if you would like to submit a guest post to WPLift, we'd love to hear from you. Please get in touch.

Siteground Hosting
Does WPLift load fast for you? That’s because we use Siteground for hosting, WPLift readers can click here to get up to 60% off hosting for your site.

Disclosure: This page may contain affiliate links for which we will receive compensation if a purchase is made.

1 Star2 Stars3 Stars4 Stars5 Stars (No Ratings Yet)
Leave Yours +

No Comments

Comments are closed.

  • Comments are Closed

Our Sponsors

SEND ME FREE WORDPRESS STUFF!

Join our Newsletter to Receive 6 Free WordPress Themes

We will also send you our weekly Newsletter packed with the Latest WordPress Content.

We will look after your email & Never Spam!

You have Successfully Subscribed!