首页 > 解决方案 > 仅将脚本应用于一级和二级类别 WooCommerce

问题描述

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

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

我只需要将此脚本应用于类别“汽车”和类别“宝马”,因此仅适用于第一级和第二级类别。

我能怎么做?

标签: phpwordpresswoocommercehierarchicaltaxonomy-terms

解决方案


您将在下面找到 3 个条件函数,可让您检查一个术语是否来自:

  • 仅限第一级产品类别
  • 仅限第 2 级产品类别
  • 1 级或 2 级产品类别

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

代码在您的活动子主题(或活动主题)的functions.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 级类别:
是 “帽衫”是 1 级或 2 级类别:
是 “李维斯”是 1 级或 2 级类别:否


推荐阅读