Last active
October 4, 2021 08:43
-
-
Save neilgee/37a7392af2fb699178a9b9c1fca811b7 to your computer and use it in GitHub Desktop.
Hide WooCommerce Product Categories
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php //<~ dont add me into functions.php | |
add_action( 'woocommerce_product_query', 'prefix_custom_pre_get_posts_query' ); | |
/** | |
* Hide Product Cateories from targetted pages in WooCommerce | |
* @link https://gist.github.com/stuartduff/bd149e81d80291a16d4d3968e68eb9f8#file-wc-exclude-product-category-from-shop-page-php | |
* | |
*/ | |
function prefix_custom_pre_get_posts_query( $q ) { | |
if( is_shop() || is_page('awards') ) { // set conditions here | |
$tax_query = (array) $q->get( 'tax_query' ); | |
$tax_query[] = array( | |
'taxonomy' => 'product_cat', | |
'field' => 'slug', | |
'terms' => array( 'cat1', 'cat2' ), // set product categories here | |
'operator' => 'NOT IN' | |
); | |
$q->set( 'tax_query', $tax_query ); | |
} | |
} |
Can confirm it does indeed work ...
Hi, i'll have two pages displaying products, one /catalog/ (the shop page) and one /pre-orders/ (for preorders, ofc).
I've added "preorders" as a category alongside the others (music genres), and tried the following:
`add_action( 'woocommerce_product_query', 'prefix_custom_pre_get_posts_query' );
function prefix_custom_pre_get_posts_query( $q ) {
if( is_shop() || is_page('catalog') ) { // set conditions here
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'preorders' ), // set product categories here
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
if( is_page('preorders') ) { // set conditions here
$tax_query = (array) $q->get( 'tax_query' );
$tax_query[] = array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => array( 'breakbeat', 'downtempo', 'ambient', 'electro', 'house', 'acid-house', 'deep-house', 'tech-house', 'uk-garage', 'minimal', 'micro-house', 'techno', 'acid-techno', 'deep-techno', 'dub-techno', 'minimal-techno', 'new-beat', 'progressive' ), // set product categories here
'operator' => 'NOT IN'
);
$q->set( 'tax_query', $tax_query );
}
}`
But it doesn't work. How can i prevent the items belonging to the "preorders" category to display on the /catalog/ page while preventing everything BUT items belonging to the preorders category to display in the /preorders/ page?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello my friend
the code you provided doesn't work
can you check if it works