Are you a GenerateCustomer?

Do you have an active GP Premium or GenerateBlocks Pro license key?

Create a GenerateSupport account for GeneratePress and GenerateBlocks support in one dedicated place.

Create an account
Already have a GenerateSupport account? Login

Just browsing?

Feel free to browse the forums. Support for our free versions is provided on WordPress.org (GeneratePress, GenerateBlocks).

Want to become a premium user? Learn more below.

Exlude pages from search results

  • Hi,
    I checked the forum to exclude pages from search results and found this

    
    function exclude_post_types_from_search( $query ) {
        if ( is_search() && $query->is_main_query() ) {
            $query->set( 'post_type', 'post' );
        }
    }
    add_action( 'pre_get_posts', 'exclude_post_types_from_search' );

    It limits search results to posts. I tried changing the code so that the search result will exclude pages but show result from posts and other post types.

    Could u give me a hand for the code? I’d like to exclude pages only.

  • Hi there,

    Try this:

    
    function exclude_post_types_from_search( $query ) {
        if ( is_search() && $query->is_main_query() ) {
            $query->set('post_type', array( 'post', 'product' ));
    
        }
    }
    add_action( 'pre_get_posts', 'exclude_post_types_from_search' );
  • thanks Yin but I still see pages in the search results.

  • In that case, go back to the original code and add all the post types you want to show instead of excluding pages.

    I’ve updated the code, you can keep on adding the post types.

  • great, thanka a lot Ying

  • No Problem 🙂

Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.