Add Custom Post Type to Main WordPress Loop

To add your custom post type to the main WordPress loop, just add the following code to your functions.php file.

function add_post_types_to_loop($query) {
    if ($query->is_main_query() && $query->is_front_page()) {
        $query->set('post_type', array('post', 'YOUR_POST_TYPE'));
    }
}

add_action('pre_get_posts', 'add_post_types_to_loop');

What’s happening: We’re creating a small filter to run when WordPress gets the latest posts. We check if it’s the main feed AND the front page, then add in our custom post type. The part that goes array('post', 'YOUR_POST_TYPE') is where you can add your custom post type, or post types if you have more than one.

Also Add to RSS Feed

If you want to add your new post type to the main feed, all it takes is a small edit to the code above that checks if the query is also for the RSS feed, with this: $query->is_feed().

function add_post_types_to_loop_and_feed($query) {
    if ($query->is_feed() || $query->is_main_query() && $query->is_front_page()) {
        $query->set('post_type', array('post', 'YOUR_POST_TYPE'));
    }
}

add_action('pre_get_posts', 'add_post_types_to_loop_and_feed');

Follow IP on Twitter Like IP on Facebook

Advertisement