Skip to content

Instantly share code, notes, and snippets.

@jonbrockett
Created June 10, 2021 14:10
Show Gist options
  • Save jonbrockett/00f742f1875e2a9aa7f48e94e0de0cbd to your computer and use it in GitHub Desktop.
Save jonbrockett/00f742f1875e2a9aa7f48e94e0de0cbd to your computer and use it in GitHub Desktop.
Disable Searching for an Empty String in WordPress Search
/** Show 'Nothing Found' for an empty search instead of all posts/pages (Helps with Accessibility) */
require_once 'library/search-empty-disable.php';
<?php
/**
* Halt the main query in the case of an empty search
*
* If someone searches blank, they expect to get a blank page.
* This helps people with disabilities to follow their intention.
*/
add_filter( 'posts_search', function( $search, \WP_Query $q )
{
if( ! is_admin() && empty( $search ) && $q->is_search() && $q->is_main_query() )
$search .=" AND 0=1 ";
return $search;
}, 10, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment