Create custom post type - Wordpress Example

In wordpress, you can easily create a custom post type manually. The problem may be with using a plugin is that your custom post type will be disappear in case of plugin is deactivated.

But any data in your custom post type will still be there, In this scenario your custom post type will be unregistered and will not be accessible from the admin area.

If you don’t want to install plugin then you can manually create your custom post type by just adding simple code in your theme’s “functions.php” file.

The code is given below:

<?php// Our custom post type functionfunction create_posttype() { register_post_type( 'Products', // CPT Optionsarray('labels' => array('name' => __( 'Products' ),'singular_name' => __( 'Products' )),'public' => true,'has_archive' => false,'rewrite' => array('slug' => 'greek-yogurt/%product_categories%'), ));}// Hooking up our function to theme setupadd_action( 'init', 'create_posttype' );?>

What exactly this code perform is that it register a post type “Products” with an array of arguments. These array arguments are the options of your custom post types.

This array has two parts, the first part is labels, which is an array itself. Whereas the second part generally contains other arguments like public visibility, slug, has archive, that will be used in URL’s for this post type.

The above code contains a small part of code. Take a look at detailed piece of code that will add more options to your custom post type.

<?php/** Creating a function to create our CPT*/function create_post_type_product() {// Set UI labels for Custom Post Typeregister_post_type( 'product',array('labels' => array('name' => __( 'Products' ),'singular_name' => __( 'Products' ),'add_new' => __( 'Add New' ),'add_new_item' => __( 'Add New Product' ),'edit' => __( 'Edit' ),'edit_item' => __( 'Edit Product' ),'new_item' => __( 'New Product' ),'view' => __( 'View Product' ),'view_item' => __( 'View Product' ),'search_items' => __( 'Search Products' ),'not_found' => __( 'No Products found' ),'not_found_in_trash' => __( 'No Products found in Trash' ),'parent' => __( 'Parent Product' ),), // Set other options for Custom Post Type 'public' => true, 'has_archive' => false, 'supports' => array('title','page-attributes','revisions','thumbnail'), 'hierarchical' => false, 'rewrite' => array( 'slug' => 'greek-yogurt/%product_categories%' ), 'query_var' => true, 'menu_icon' => 'dashicons-carrot'));}add_action( 'init', 'create_post_type_product' );function create_product_taxonomies() {$labels = array('name' => _x( 'Product Categories', 'product_categories' ),'singular_name' => _x( 'Product Category', 'product_category' ),'search_items' => __( 'Search Product Categories' ),'all_items' => __( 'All Product Categories' ),'parent_item' => __( 'Parent Product Category' ),'parent_item_colon' => __( 'Parent Product Category:' ),'edit_item' => __( 'Edit Product Category' ),'update_item' => __( 'Update Product Category' ),'add_new_item' => __( 'Add New Product Category' ),'new_item_name' => __( 'New Product Category Name' ),'menu_name' => __( 'Product Categories' ), );/* A hierarchical CPT is like Pages and can have * Parent and child items. A non-hierarchical CPT * is like Posts.*/ $args = array( // Set this to 'false' for non-hierarchical taxonomy (like tags) 'hierarchical' => true, 'labels' => $labels, 'show_ui' => true, 'show_admin_column' => true, 'query_var' => true, 'rewrite' => array( 'slug' => 'greek-yogurt'), ); // Registering your Custom Post Type register_taxonomy( 'product_categories', array( 'product' ), $args );}add_action( 'init', 'create_product_taxonomies', 0 );function product_title() {global $post, $title, $action, $current_screen;if($post->post_type == 'product'){$title = str_replace('Post','Product',$title);}}/* Hook into the 'init' action so that the function* Containing our post type registration is not * unnecessarily executed. */add_action( 'admin_head', 'product_title' );?>

Here you can see, we have added more options to the custom post type with this code. We have also associated this custom post type with a custom taxonomy called “create_product_taxonomies”.

Also notice that the part where we have set the hierarchical value to be true. we have true to it because we want our custom post type to behave like pages.

you can also find your theme’s text domain in inside “style.css” file in your theme’s directory. Text domain will be mentioned in the header of the file.

How to display a Custom Post Type on your site in WordPress

WordPress comes with some important built in features that supports for displaying your custom post types. Once you have added a new items into your custom post type, it should be displayed on your website.There are lots of methods that you can use, each methods has its own benefits.

Displaying Custom Post Type using default Archive Template

Firstly you need to visit your wordpress admin bar (Dashboard).

Appearance  == >  Menus.

Now add a custom link to your menu. This custom link is the link to your custom post types.

If you are using SEO friendly permalinks then your custom post type’s URL will most likely be something like this.

http://www.example.com/products/

And in another case where you are not using SEO friendly permalinks, then your custom post type URL’s like this.

http://www.example.com/?post_type=products/

You can replace “example.com” to your domain name and products with your custom post type name.

Save your menu and then visit the front end of your website. You will see the new menu you added.

Just click on it, it will display your custom post type archieve pages using the “archieve.php” template file in your theme.

CPT(custom post type) Archives and Single Entries by using Custom Templates

If you don’t like the appearance of the archive page for your custom post type then you can use dedicated template for custom post type archive. To do that all you need to do is create a new file in your theme directory and name it “archive-products.php”.

Replace products with the name of your custom post type.

For this, you can easily make a file named as “archieve-product.php”. Copy the contents of archieve.php and paste it into the “archieve-product.php” file.

Now start modifying it to meet your needs. In this way whenever the archieve page for your custom post type is accessed, this template will be used to display it.

Similarly you can also perform this type of action to create a custom template for your post types single entry display.

To perform this action you need to make a file named as “single-product.php” in your themes directory.

Copy the contents of “single.php” file and paste its code into the “single-product.php” file.  And then start modifying it to meet your needs.

 

How to display Custom Post Types on the front page in WordPress

There are many advantages of using custom post types but one major advantage of using custom post type is that it keeps your custom types away from regular posts.

But if you want to display your custom post type among with regular posts then you can do so by adding this code into your themes “functions.php” file.

<?phpadd_action( 'pre_get_posts', 'add_my_post_types_to_query' ); function add_my_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 are familiar with the coding and would like to run loop queries in your templates, then here is how to do that.

you can retrieve items from a custom post type just by querieying to the database.

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

In the above code, we have defined the post type and also posts per page in the arguments for our “WP_Query_Custom” class.

After that we ran our query, we can retrieved the posts and displayed them inside the loop.

In Widgets How To Display Custom Post Types

You see a widget area in your wordpress, by default this widget area generally contains the recent posts to display.

But this widget does not allow you to choose a custom post type. If you want to display the latest entries of your newly created custom post types in widget then how could it accomplished.

Here we will show you how could you do this. Firstly you need to install and activate a plugin named as “Ultimate Posts Widget”.

Upon activation of your plugin, you need to visit Appearance  ==>  Widget

Drag and drop the “Ultimate Posts Widget” to a sidebar. Now this widget will allow you to show recent posts from any posts types.

You can also display post excerpt with a read more link or even show a featured image next to post title. Apply save changes and see the widget in action on your websites.