0

I'm trying to add a custom post type into the seach facility so that it searches those posts as well as the pages on a site.

I have seen the pre_get_posts function and have it set up like the below in my themes functions.php file but its not firing at all. I have put get_current_screen() function in there to test but it doesn't return anything.

function searchAll($query) {
  if ( !is_admin() && $query->is_main_query() ) {
    if ($query->is_search) {
      $query->set('post_type', array( 'post', 'movie' ) );
    }
  }
}

add_action('pre_get_posts','searchAll');

I also tried to just have the $query->set('post_type', array( 'post', 'movie' ) ); line not in any of the if statements but nothing is happening. What am I doing wrong?

Please help!

5
  • Function seems ok, it should work. Try adding add_action( 'pre_get_posts', 'searchAll', 1 );
    – Robert hue
    Commented Oct 28, 2014 at 16:45
  • $query->is_search should be $query->is_search()
    – Milo
    Commented Oct 28, 2014 at 16:51
  • Just tried, but no good! I'm thinking there must be some error in the theme somewhere. Commented Oct 28, 2014 at 16:54
  • Try add_action( 'pre_get_posts', 'searchAll', 999 ); Commented Oct 28, 2014 at 16:56
  • Try @Milo's suggestion. $query->is_search()
    – Robert hue
    Commented Oct 28, 2014 at 16:57

1 Answer 1

0

Try adding this to your functions.php.

function my_custom_get_posts( $query ) {
  if ( is_admin() || ! $query->is_main_query() )
    return;

  if ( $query->is_search() ) {
    $query->set( 'post_type', array( 'post', 'movie' ) );
  }

}
add_action( 'pre_get_posts', 'my_custom_get_posts', 1 );

Also make sure you do not have any other pre_get_posts action overwriting this function's effect.

2
  • *smacks-hand-against-head... I didn't even think about if the function was already in use. I checked, and it was, so just added my post type to the existing function. Now it works. feel a bit silly now. Commented Oct 28, 2014 at 16:58
  • We all make fair share of such mistakes. :)
    – Robert hue
    Commented Oct 28, 2014 at 17:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.