Home Forums General Issues Pre_get_posts loop


Pre_get_posts loop

  • Hi there,

    I want to exclude my search results by post ids.
    Therefor I created an relation field as option.

    But the get_field is probably also using pre_get_posts and gets into an infinite loop.
    This is my code.

    function wpb_search_filter( $query ) {
       if(!is_admin() && is_search()){
        $excluded_post_ids = get_field('exclude_from_search','option');
          if ( $query->is_search && !is_admin() ){
            $query->set( 'post__not_in', $excluded_post_ids );
      return $query;
    add_filter( 'pre_get_posts', 'wpb_search_filter' );

    How do I set the proper IF statement?

    Thanks in advance!

  • try adding a check to see if it is then main query

    function wpb_search_filter( $query ) {
       if(!is_admin() && is_search() && $query->is_main_query()){
        //..... code continues
  • Hi John,

    Thanks for the incredibly fast and accurate answer. Problem solved!


Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.