Using pre_get_posts / meta_query on search page?
-
We have a website which displays classes, a custom post type. Each class can have an expiration date (unix timestamp).
I have the following code which worked in the past, which is simply meant to exclude expired classes from the search results page (and many other places of the website):
function class_hide_expired_frontend( $query ) { if ( is_admin() ) return; // Do not filter secondary queries, only the main query and search queries if ( !$query->is_main_query() && !$query->is_search ) return; // Do not alter the existing meta_query if another filter is applied if ( $query->get('meta_query') ) return; // If the query affects classes, exclude expired ones if ( $query->get('post_type') == 'class' || $query->is_search() || $query->get('taxonomy') == 'class-group' ) { $query->set( 'meta_query', array( 'relation' => 'OR', array( 'key' => 'date-timestamp', 'value' => time(), 'compare' => '>', ), array( 'key' => 'date-timestamp', 'value' => '0', 'compare' => '=', ), )); } return $query; } add_action( "pre_get_posts", 'class_hide_expired_frontend', 90 );
The above meta_query checks that the “date-timestamp” field (expiration date) is either 0 (no expiration) or greater than the current time.
This code seems to be ignored when using Better Search. I assume this is because Better Search modifies the SQL statements directly and is incompatible with meta_query.
Do you have any suggestions or alternatives?
Thanks
- The topic ‘Using pre_get_posts / meta_query on search page?’ is closed to new replies.