[Resolved] how to fix empty or blank searches from displaying all posts

Home Forums Support how to fix empty or blank searches from displaying all posts

Viewing 6 posts - 1 through 6 (of 6 total)
  • Author
    Posts
  • #1193435
    anand

    any workaround for this

    #1193965
    Leo
    Staff
    Customer Support

    Hi there,

    Not quite sure if I understand.

    Can you explain a bit more?

    I’m not seeing a search in the page you’ve linked.

    Let me know 🙂

    #1194054
    Thornbrand

    Hi Anand and Leo,

    I’ve noticed this in the past as well. This isn’t really a theme issue, but is the default behavior of WordPress. I’m not sure if it’s bug or a feature. 😉

    I’ve been using the code below in my functions.php file to halt the query if it is blank.

    /**
     * Halt the main query in the case of an empty search 
     */
    add_filter( 'posts_search', function( $search, \WP_Query $q )
    {
        if( empty( get_search_query() ) && $q->is_search() && $q->is_main_query() )
            $search .=" AND 0=1 ";
    
        return $search;
    }, 10, 2 );

    With the default GeneratePress theme, it should return the standard no-results page.

    Hope this helps!

    #1194060
    Leo
    Staff
    Customer Support
    #1194328
    anand

    THANKS

    works wonderful

    returns
    Nothing Found
    Sorry, but nothing matched your search terms. Please try again with some different keywords.

    #1374712
    byo

    hi,
    This code return empty posts and pages if we try to filter posts in admin dashboard either we filter per category or per date,
    I’ve add this !is_admin() so the code does not mess with the dashboard.
    If someone have a better code or better approach to how wordpress handle empty search please share.

    /**
     * Halt the main query in the case of an empty search 
     */
    add_filter( 'posts_search', function( $search, \WP_Query $q )
    {
        if( empty( get_search_query() ) && !is_admin() && $q->is_search() && $q->is_main_query() )
            $search .=" AND 0=1 ";
    
        return $search;
    }, 10, 2 );
Viewing 6 posts - 1 through 6 (of 6 total)
  • You must be logged in to reply to this topic.