Theres a way to use $query->set('tax_query', ...) in pre_get_posts filter? for example next code is not altering the query. Note that I’m building $taxonomies from and custom search.
function custom_search_filter($query) {
...
// array('taxonomy' => 'category', 'field' => 'id', 'terms' => array( 41,42 ), 'operator' => 'IN')
$taxonomies = implode(',', $taxonomy_arr);
// https://wordpress.stackexchange.com/questions/25076/how-to-filter-wordpress-search-excluding-post-in-some-custom-taxonomies
$taxonomy_query = array('relation' => 'AND', $taxonomies);
$query->set('tax_query', $taxonomy_query);
}
return $query;
}
add_filter( 'pre_get_posts', 'custom_search_filter', 999 );
Thanks in advance.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The $query variable in the filter represents a WP_Query object, so you shouldn’t be passing a new WP_Query object into the method for setting that object’s properties.
The question you copied code from was incorrectly using the filter, which i feel is the crux of your issue.
Yes, tax_query can be used inside a pre_get_posts (or similarly parse_request) filter/action.
Here is an example:
Specify a custom taxonomy for search queries
function search_filter_get_posts($query) {
if ( !$query->is_search )
return $query;
$taxquery = array(
array(
'taxonomy' => 'career_event_type',
'field' => 'id',
'terms' => array( 52 ),
'operator'=> 'NOT IN'
)
);
$query->set( 'tax_query', $taxquery );
}
add_action( 'pre_get_posts', 'search_filter_get_posts' );
Method 2
Tax queries require you to also set the tax_query object in the query since the query has already been parsed. See my answer for Modify Taxonomy pages to exclude items in child taxonomies.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0