I am trying to modify the_loop
output from a plugin. I’ve looked into pre_get_posts
, which definitely works, but I need to filter the loop by a custom taxonomy. I can do this with $query->set('tax_query',$my_tax_new_query)
, but the problem is this overrides any previous taxonomy queries that may have been set. It applies my query INSTEAD of the former query instead of IN ADDITION TO IT. How can I apply an additional taxonomy filter to the loop without wiping out the previous query?
EDIT:
For example:
function myplugin_filter_the_loop($query) {
$taxonomy = 'hobbies';
$exclude_terms = array('biking','swimming','horsebackriding');
$query->set('tax_query',$exclude_terms)
}
add_filter('pre_get_posts','myplugin_filter_the_loop');
This works, but it will REPLACE any previously defined tax_query
on the loop.
EDIT2:
Alternative using posts_where
:
function myplugin_filter_the_loop($where) {
$relationship_ids = array(97,98,99);
foreach ( $relationship_ids as $id ) :
$where .= " AND ( wp_posts.ID NOT IN ( SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id IN ($id)"
endforeach;
}
add_filter('posts_where','myplugin_filter_the_loop');
For this to work, I’d just need to get the corresponding relationship id by term_id or slug, etc.
Use
$tax_query = $query->get( 'tax_query' );
to get the existing tax_query, modify it by adding your changes, then use$query->set( 'tax_query', new_$tax_query
); to put the whole thing back.