the code you show is using the category taxonomy and not the custom taxonomy you created.
Look at the code for custom taxonomies in the wp_query docs:
https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters
Thanks Steven for your help.
But honestly I don’t understand how to implement “Taxonomy_Parameters” into my code. Can you help me, please!
Many thanks.
Try this:
function exclude_cat( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
if ( is_post_type_archive( 'book' ) ) {
$tax_query = $query->get( 'tax_query' ) ?: array();
$tax_query[] = array(
'taxonomy' => 'cat_book',
'field' => 'id',
'terms' => array( 30, 31 ),
'operator' => 'NOT IN',
);
$query->set( 'tax_query', $tax_query );
}
}
return $query;
}
add_action('pre_get_posts','exclude_cat');
I wrote it blind, so make a backup of your functions file before adding this, in case I made a type-o.
Thank you, thank you… thank you very much JakePT for your help 🙂
Hi there,
This is half way to solving my problem so thank you very much for sharing.
I can only get this code to work if I remove the <if> statements. I need them otherwise the function is applied to all pages in the site, not just the home page.
I have a static front page configured.
This is the code I have been trying to use:
add_action('pre_get_posts','exclude_cat');
function exclude_cat( $query ) {
if ( !is_admin() && $query->is_main_query() ) {
$tax_query = $query->get( 'tax_query' ) ?: array();
$tax_query[] = array(
'taxonomy' => 'st_category',
'field' => 'id',
'terms' => array( 115 ),
'operator' => 'NOT IN',
);
$query->set( 'tax_query', $tax_query );
}
return $query;
}
I have also tried the following <if> statements with no success:
if( $query->is_page( array( 113, 'portfolio', 'Portfolio' ) ) ) {
if( $query->is_home() ) {
if( $query->is_front_page() ) {
It works perfectly without the <if> statements! What is going on?
Please help if you can – thank you!