How to Add Custom Post Types to Your Home Page
Custom Post Types in WordPress provide a powerful way to improve the functionality of your website. You can create new custom post types to create a personal experience for your website viewers. If you use multiple custom post types on your blog, you can manage different types of content. But, custom post types aren’t automatically added to the site’s main loop. So, custom post types will not be shown automatically on the home page.
If you want to show a mix of posts and articles from custom post types on the home page, you can do this with just a few lines of code. The code modifies the main query to include your custom post type. It uses ‘pre_get_posts’ action hook for this.
Best Managed WordPress Hosting
WPEngine is the best and most secure managed hosting providerfunction cpt_on_blog_page($query) {
if ( is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'custom_post_type' ));
}
}
add_action( 'pre_get_posts', 'cpt_on_blog_page' );
If you have multiple custom post types, you can add all in the post type array in the code. For example, check the code added below.
function cpt_on_blog_page($query) {
if ( is_home() && $query->is_main_query() ) {
$query->set( 'post_type', array( 'post', 'custom_post_type1', 'custom_post_type2', 'custom_post_type3' ));
}
}
add_action( 'pre_get_posts', 'cpt_on_blog_page' );
Add the code in the functions.php file of your WordPress theme.
The above function tells WordPress to include a custom post type in the home page loop before building the main query. It also adds articles to the main feed of your WordPress blog.
Also read: How to Add Custom Post Types to Your Main WordPress RSS Feed
Always take a backup of your website before making changes to theme files. You also need to test the changes on a staging site or local environment first. If you are not an experienced developer, you can always hire me to make adjustments to your WordPress theme and enhance the website.
Leave a comment
Comment policy: We love comments and appreciate the time that readers spend to share ideas and give feedback. However, all comments are manually moderated and those deemed to be spam or solely promotional will be deleted.