Add Custom Post Type to Loop (and RSS)

If you’re running a site like a blog, then the below comes in incredibly handy for handling multiple posts types, for example, posts, videos, freebies and so on.

The code below says “if this is the RSS feed or the main loop on the blog, then pull in posts and our other custom post type“.

function add_cpt_to_loop_and_feed($query) {
    //---- Don't run in admin area
    if(!is_admin()) {
        // Add custom post types
        if ($query->is_feed() || ($query->is_main_query() && $query->is_front_page())) {
            $query->set('post_type', array('post', 'MY_CPT'));
        }

        // Return query
        return $query;
    }
}

add_action('pre_get_posts', 'add_cpt_to_loop_and_feed');

Inspirational Newsletter


Join the newsletter to get the best articles, tutorials and exclusive freebies every two weeks.

No spam. You can unsubscribe at any time.