The default installation of WordPress comes with different content types to help you manage your content. The two default content types are: post and pages. However, WordPress is very flexible and allows you to add different post types that can be managed separately. For example, someone who is using WordPress to provide an online course may have additional post types such as ‘course’ and ‘lesson’. With these new post types, you can completely customize the data and presentation of your content. Similarly you can create custom post types of all kinds of content such as movie reviews, ecommerce product listings, real estate listings, etc.

With some work, you can create a new custom post type for your own WordPress website. We will learn how to do so in another article. For this article, let’s just assume that you already have a custom post type, say ‘lesson’. It could have been added by your web developer, by a plugin, or it could be a part of a new theme that you installed. All is fine till here. Now go on with your job and are publishing regular blog posts on your blog and are also adding new lessons using the custom post type.

custom-post-types

Problem

The problem you face is that on your blog home page, the regular blog posts are appearing, but the lessons created with the custom posts type ‘lesson’ are missing. How do you solve this and make all the regular blog posts and custom posts show up on the home page?

Solution

WordPress provides a very neat way to do this. Follow these steps to resolve this problem:

  1. Open the file named functions.php in your theme folder
  2. Add the following function and action somewhere before the end of the folw:
add_action('pre_get_posts', 'add_my_custom_post_type');

function add_my_custom_post_type($query) {

if(

empty($query->query['post_type'])

or $query->query['post_type'] === 'post'

){

$query->set('post_type', array('any'));

}

}

The above function will include all the post types while preparing the posts to be displayed. Note the array ‘any’. This tells WordPress to get all the post types. However, if you had many custom post types and wanted to include only a few specific custom post types, then you can specify these post types in the array:

add_action('pre_get_posts', 'add_my_custom_post_type');

function add_my_custom_post_type($query) {

if(

empty($query->query['post_type'])

or $query->query['post_type'] === 'post'

){

$query->set('post_type', array('post', 'my_custom_type'));

}

}

Please feel free to provide your valuable suggestions in the comments below.

Pin It on Pinterest

Share This