繁体   English   中英

从 WooCommerce 产品类别小部件中删除父类别和子类别

[英]Removing parent and child categories from WooCommerce Product Category widget

我有以下代码从 WooCommerce 产品类别小部件中为除管理员和批发客户(自定义用户级别)之外的所有用户删除“批发类别”(通过 slug)。

这很好用,但是它只会删除父类别并保留所有子类别。 如何删除“批发类别”的子类别?

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

谢谢

尝试这样的事情......

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

请检查以下将完成工作的代码。 代替 YOUR_PAGE_SLUG,您需要替换为您的页面 slug,并将“woo”替换为您需要隐藏的类别的产品类别 slug

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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