Skip to content

How to Add Custom Post Types in WordPress Latest Posts Feed

WordPress comes with a couple of default post types the most apparent of these being the standard post type called posts. This type is what we use to create blogposts and is usually what is displayed in the home or posts feed. However, it is possible to create additional types that function similar to the default posts type, or even import posts into a custom post type.

Doing this may for example useful for blogs that host content on a few disparate topics which for content management and user navigation could benefit from being housed in separate post types. This way each post type can have its own distinct archive pages as well as additional features it may or may not need such as categories and tags.

Nevertheless, in certain instances one may want to have content from different post types to be displayed together. Such is the case with the latest post feeds, which shows all the posts in a blog sequentially, usually with the newest posts listed first.

In most themes, only posts from the standard post type are included in this feed. Consequently, posts from custom post type will not be displayed in the latest posts feed. With a little code snippet using the pre_get_posts filter hook we can however instruct WordPress to include the custom post types posts into the main query of blog posts.

Code Snippet to Add Custom Post Types to Main Blog Feed

/**
 * This function modifies the main WordPress loop to include 
 * custom post types along with the default 'post' post type.
 *
 * @param object $query The main WordPress query.
 */
function tg_include_custom_post_types_in_main_loop( $query ) {
    if ( $query->is_main_query() && $query->is_home() && ! is_admin() ) {
        $query->set( 'post_type', array('post', 'news') );
    }
}
add_action( 'pre_get_posts', 'tg_include_custom_post_types_in_main_loop' );

Instructions on how to use this snippet:

  1. Change the news item with your custom post type. You can add multiple types by separating them using a comma, i.e 'post', 'news', 'sports', 'downloads'
  2. Add this code to your theme using the code snippets plugin, or add it manually into your functions.php file.

Code courtesy of: https://thomasgriffin.com/how-to-include-custom-post-types-in-wordpress-archive-pages/

Tags:
Share:

Leave a Reply

Feel free to share your comments or questions with me. I may not be able to respond immediately so please check later once I've approved your comment.

Your email address will not be published. Required fields are marked *

Kelvin Kathia

Kelvin Kathia is a writer that's passionate about sharing solutions to everyday tech problems. He's the founder and editor of Journey Bytes, a tech blog and web design agency. Feel free to leave him comments or questions regarding this post, or by leaving him a message on the contact page. If you found his content helpful, a donation is much appreciated.