Custom Post Types In The Loop: Using `pre_get_posts`, Refined

[deprecated permalink=””]

Third verse, almost the same as the first.

Using `request` data means that requests that end up with a 404 or are a search produce weird results with navigation menus, among other oddities. So I’m back to using `pre_get_posts` to include custom post types, with a few refinements.

10 thoughts on “Custom Post Types In The Loop: Using `pre_get_posts`, Refined”

  1. hi – I’m a bit confused – does this go in functions.php or loop.php ?

    what should I change to match my settings?
    I’m trying to get my custom posts types to appear in category pages.

  2. Try this in functions.php:

    function ucc_pre_get_posts( $query ) {
    global $wp_query;
    if ( $query->is_category ) {
    $post_types = array( 'custom1', 'custom2', 'post' );
    $query->set( 'post_type', $post_types );
    return $query;
    add_action( 'pre_get_posts' , 'ucc_pre_get_posts' );

  3. I just found this code and it works ok – is it the same thing? will try yours too

    function my_get_posts( $query ) {

    if ( is_home() || is_category() || is_archive() && false == $query->query_vars['suppress_filters'] )
        $query->set( 'post_type', array( 'post', 'quotes' ) );
    return $query;


  4. Just a minor correction: pre_get_posts is an action, not a filter. You should be hooking in with add_action() instead of add_filter(), and the callback function shouldn’t return anything.

    The $query variable is passed by reference, so it isn’t a copy of the $query variable inside WP_Query::get_posts(), it’s a link directly to it. Any changes to $query inside the callback function will be applied to the variable in the calling function.

    1. I was using the sw_custom_post_type_includes filter below to add custom post types to my archive page. And the navigation menu was resetting as if nothing is defined. It was just listing the pages of the site.

      (I give more detail to help someone find your solution too)
      Thank you again.

Leave a Reply