简体   繁体   中英

Removing parent and child categories from WooCommerce Product Category widget

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

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;
}

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM