General purpose “Show no initial results” for Views custom searches

When you want a Google-style search where no results are initially shown you can use the following code, which will prevent results being displayed until a filter is applied.

Works with custom field filters, taxonomy filters, and/or text field searches.

/**
 * No initial results
 *
 * Don't show View results until a filter has been applied
 * 
 * Tests for custom field filters, taxonomy filters, or text searches
 */
function tssupp_no_initial_results( $query_results, $view_settings, $view_id ){
  
	$target_views = array( 226 ); // Edit to add IDs of Views to add this to

    if ( in_array( $view_id, $target_views ) ) {
  
        // if there is a search term set
        if ( !isset( $query_results->query['meta_query'] ) && !isset( $query_results->query['tax_query'] ) && !isset( $query_results->query['s'] ) ) {
            $query_results->posts = array();
            $query_results->post_count = 0;
            $query_results->found_posts = 0;
        }
    }
  
    return $query_results;
}
add_filter( 'wpv_filter_query_post_process', 'tssupp_no_initial_results', 10, 3 );

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments