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:
- 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'
- 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/