• I’ve added a hidden field, “post_type” to my search form and entered the name of the post_type as the value. Normally, this just works. This time, it’s working for the most part, but there are a few pages that keep sneaking into the results. By that I mean there might be 15 results from the custom post type and then one or two results that are wordpress pages. I’ve gone into the database and examined these pages in the wp_posts table and confirmed that the post_type is indeed ‘page’.

    I tried additionally adding this code to restrict search results to single custom post type.

    function my_query_modifications( $query ) {
    
      $post_type = $_GET['post_type'];
    	if (!$post_type) {
    		$post_type = 'any';
    	}
        if ($query->is_search) {
            $query->set('post_type', $post_type );
        }
    }
    add_action('pre_get_posts', 'my_query_modifications');

    It hasn’t helped. Anyone seen this before or have any ideas of what I might try?

    Thanks!

Viewing 1 replies (of 1 total)
  • Hi newvibe,

    how do you do? It seems that your pre_get_posts hook is working fine only that it queries pages as well when it sounds like it should not.

    Can you try to use the following code instead:
    $query->set(‘post_type’, array( ‘post’, $post_type ) );

    so that it now appears:

    function my_query_modifications( $query ) {
    
      $post_type = $_GET['post_type'];
    	if (!$post_type) {
    		$post_type = 'any';
    	}
        if ($query->is_search) {
            $query->set('post_type', array('post', $post_type));
        }
    }
    add_action('pre_get_posts', 'my_query_modifications');

    That should only display results of custom post_type that aren’t pages. Please let us know how it goes. Thank you!

Viewing 1 replies (of 1 total)
  • The topic ‘Cannot Limit Search Results to Custom Post Type’ is closed to new replies.