skip to Main Content

I have the following code that removes the “wholesale-category” (via slug) from the WooCommerce Product Category widget for all users except for administrators and wholesale_customer (custom user level).

This works great, however it only removes the parent category and leaves all child categories. How can I remove the child categories of “wholesale-category” too?

// Woocommerce - Removes category link from woocommerce product category widgets so they are not seen
add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );

function get_subcategory_terms( $terms, $taxonomies, $args ) {

  $new_terms = array();

  $category_to_check = get_term_by( 'slug', 'wholesale-category', 'product_cat' );

  // if a product category and on the shop page
  if ( in_array( 'product_cat', $taxonomies ) && ! ( current_user_can( 'wholesale_customer' ) || current_user_can( 'administrator' ) ) ) {

    foreach ( $terms as $key => $term ) {

      if ( ! in_array( $term->slug, array( 'wholesale-category' ) ) ) {
        $new_terms[] = $term;
      }

    }

    $terms = $new_terms;

  }

  return $terms;
}

Thanks

2

Answers


  1. Please check with below code that will do the work. in place of YOUR_PAGE_SLUG you need to replace with your page slug and replace “woo” with the product category slug of the category you need hidden

    add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );
    function get_subcategory_terms( $terms, $taxonomies, $args ) {
      $new_terms = array();
      // if a product category and on the shop page
     // to hide from shop page, replace is_page('YOUR_PAGE_SLUG') with is_shop()
      if ( in_array( 'product_cat', $taxonomies ) && ! is_admin() && is_page('YOUR_PAGE_SLUG') ) {
        foreach ( $terms as $key => $term ) {
          if ( ! in_array( $term->slug, array( 'woo' ) ) ) {
            $new_terms[] = $term;
          }
        }
        $terms = $new_terms;
      }
      return $terms;
    }
    
    Login or Signup to reply.
  2. try something like this…

    // Woocommerce - Removes category link from woocommerce product category widgets so they are not seen
    add_filter( 'get_terms', 'get_subcategory_terms', 10, 3 );
    
    function get_subcategory_terms( $terms, $taxonomies, $args ) {
    
      $category_to_check = get_term_by( 'slug', 'wholesale-category', 'product_cat' );
      if ( in_array( 'product_cat', $taxonomies ) && ! ( current_user_can( 'wholesale_customer' ) || current_user_can( 'administrator' ) ) ) {
        foreach ( $terms as $key => $term ) {
          if ( in_array( $term->slug, array( $category_to_check->slug ) ) || ( $category_to_check->term_id == $term->parent ) ) {
            unset($terms[$key]);
          }
        }
      }
      return $terms;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search