Help with PHP snippet.

Status
Not open for further replies.

jemzozole

Regular Member
Joined
Jan 13, 2021
Messages
268
Reaction score
184
Hello guys. I have no idea how much I will have to pay for that but:
(WordPress + Woocommerce)

a) I have a category that has to be hidden from mypage.com/shop/ ;
b) All products from this category also shouldn't be visible on the /shop/ page ;
c) However, if a user goes directly to the category (I will have a link in the menu), there should be all products from the category listed;

I have these 2 snippets:

1. Hiding Category:
PHP:
add_filter( 'get_terms', 'ts_get_subcategory_terms', 10, 3 );
    function ts_get_subcategory_terms( $terms, $taxonomies, $args ) {
          $new_terms = array();
          // if it is a product category and on the shop page
          if ( in_array( 'product_cat', $taxonomies ) && is_shop() ) {
             foreach ( $terms as $key => $term ) {
                 if ( ! in_array( $term->slug, array( 'category' ) ) ) {        //pass the slug name here
                    $new_terms[] = $term;
                 }
          }
          $terms = $new_terms;
    }
    return $terms;
}

2. Hiding Products:
PHP:
add_action( 'woocommerce_product_query', 'ts_custom_pre_get_posts_query' );
function ts_custom_pre_get_posts_query( $q ) {
    $tax_query = (array) $q->get( 'tax_query' );
    $tax_query[] = array(
           'taxonomy' => 'product_cat',
           'field' => 'slug',
           'terms' => array( 'category'),
           'operator' => 'NOT IN'
    );
    $q->set( 'tax_query', $tax_query );
}

However, now even if I go directly to mypage.com/product-category/category, there are not my products. (They are hidden)
No products were found matching your selection.

I believe it's one line of code, but I am not a programmer, so I can not do that.

TL;DR
I want to hide a category with its products from /shop/ page but still display the products within the category page.
 
Last edited:
Status
Not open for further replies.
This thread has been auto closed due to the forum's thread age policy. Read more.
Back
Top