只在一级和二级分类中应用脚本 WooCommerce

问题描述 投票:-1回答:1

我需要在不同的特定类别上通过函数php添加一个脚本。

1个类别的例子:汽车-> Bmw -> x1。Car -> Bmw -> x1.(这只是一个例子,我有不同的分类层次结构,像这样)

我需要把这个脚本只应用于 "汽车 "和 "BMW "类别,所以只应用于一级和二级类别。

我该怎么做呢?

php wordpress function woocommerce categories
1个回答
0
投票

下面你会发现3个条件函数,可以让你检查一个术语是否来自。

  • 1级产品类别
  • 仅二级产品类别
  • 一级或二级产品类别

所有3个条件函数都可以使用产品类别的Id,Slug或名称。

// Utility function:  Get the WP_Term object from term ID, slug or name
function wc_category_to_wp_term( $term, $taxonomy ) {
    if( is_numeric( $term ) && term_exists( $term, $taxonomy ) ) {
        return get_term( (int) $term, $taxonomy );
    } elseif ( is_string( $term ) && term_exists( $term, $taxonomy ) ) {
        return get_term_by( 'slug', sanitize_title( $term ), $taxonomy );
    } elseif ( is_a( $term, 'WP_Term' ) && term_exists( $term->slug, $taxonomy ) ) {
        return $term;
    }
    return false;
}

// Conditional function to check if  if a product category is a top level term
function is_wc_cat_lvl_1( $category, $taxonomy = 'product_cat' ) {
    if( $term = wc_category_to_wp_term( $category, $taxonomy ) ) {
        return ( $term->parent === 0 ) ? true : false;
    }
    return false;
}

// Conditional function to check if a product category is a second level term
function is_wc_cat_lvl_2( $category, $taxonomy = 'product_cat' ) {
    if( ( $term = wc_category_to_wp_term( $category, $taxonomy ) ) && $term->parent !== 0 ) {
        $ancestors = get_ancestors( $term->term_id, $taxonomy );

        // Loop through ancestors terms to get the 1st level term
        foreach( $ancestors as $parent_term_id ){
            // Get the 1st level category
            if ( get_term($parent_term_id, $taxonomy)->parent === 0 ) {
                $first_level_id = $parent_term_id;
                break; // stop the loop
            }
        }
        return isset($first_level_id) && $first_level_id === $term->parent ? true : false;
    }
    return false;
}

// Conditional function to check if a product category is a first or second level term
function is_wc_cat_lvl_1_or_2( $category, $taxonomy = 'product_cat' ) {
    $lvl_1 = is_wc_cat_lvl_1( $category, $taxonomy = 'product_cat' );
    $lvl_2 = is_wc_cat_lvl_2( $category, $taxonomy = 'product_cat' );

    return $lvl_1 || $lvl_2 ? true : false;
}

代码在您的活动主题(或活动主题)的function.php文件中。经过测试,可以使用。


使用示例 - 显示产品类别术语是来自第一或第二产品类别级别。

$term1 = "Clothing"; // a 1st level category
$term2 = "Hoodies"; // a 2nd level category
$term3 = "Levis"; // a 3rd level category

echo  'Is "' . $term1 . '" a level 1 or 2 category: ' . ( is_wc_cat_lvl_1_or_2( $term1 ) ? 'YES' : 'NO' ) . '<br>'; 
echo  'Is "' . $term2 . '" a level 1 or 2 category: ' . ( is_wc_cat_lvl_1_or_2( $term2 ) ? 'YES' : 'NO' ) . '<br>';
echo  'Is "' . $term3 . '" a level 1 or 2 category: ' . ( is_wc_cat_lvl_1_or_2( $term3 ) ? 'YES' : 'NO' ) . '<br>'; 

这将输出。

"服装 "是1级还是2级类别。YES "Hoodies "是1级或2级类别吗?是 "Levis" 是 1 级或 2 级类别。不是

© www.soinside.com 2019 - 2024. All rights reserved.