php 如何在WooCommerce产品子类别中显示特定内容

i7uaboj4  于 5个月前  发布在  PHP
关注(0)|答案(2)|浏览(55)

我使用的代码需要在不同的类别页面上显示特定的内容。
我的类别具有以下结构:

    • 短裤
      • 带口袋的短裤

但是下面的代码只显示父类别(Man)和第一级子类别(Cloth)上的内容:

add_action( 'woocommerce_archive_description', 'add_slide_text',1 );
function add_slide_text() {
    $cat = get_queried_object();

    if ( is_product_category() ) {
        if ( is_product_category( 'man' ) ||  $cat->parent === 233 ) {
            echo 'Hello man';
        } elseif ( is_product_category( 'woman' ) ||  $cat->parent === 232 ) {
            echo 'Hello woman';
        } else {
            echo '';
        }
    }
}

字符串
如何强制它显示较低级别的子类别内容?例如,在“短裤”和“带口袋的短裤”(可能更低) 中?
任何帮助都很感激。

5vf7fwbs

5vf7fwbs1#

您可以使用get_term_children() WordPress function与WooCommerce产品类别自定义分类,以显示每个特定产品类别的特定文本“男人”和“女人”术语及其子女如下:

add_action( 'woocommerce_archive_description', 'add_slide_text', 1 );
function add_slide_text() {
    // Targeting WooCommerce product category archives
    if ( is_product_category() ) {
        $current_term = get_queried_object();
        $taxonomy     = $current_term->taxonomy;

        // For "man" term (and term ID 233)
        $term_man_id      = get_term_by('slug', 'man', $taxonomy)->term_id; // Get "man" term ID
        $children_man_ids = (array) get_term_children($term_man_id, $taxonomy); // Get children terms IDs
        $man_terms_ids    = array_merge( array(233, $term_man_id), $children_man_ids ); // Merge terms IDs in a unique array

        // For "woman" term (and term ID 232)
        $term_woman_id      = get_term_by('slug', 'woman', $taxonomy)->term_id; // Get "woman" term ID
        $children_woman_ids = (array) get_term_children($term_woman_id, $taxonomy); // Get children terms IDs
        $woman_terms_ids    = array_merge( array(232, $term_woman_id), $children_woman_ids ); // Merge terms IDs in a unique array

        // Conditional text display
        if ( in_array( $current_term->term_id, $man_terms_ids ) ) {
            _e('Hello man', 'woocommerce');
        } 
        elseif ( in_array( $current_term->term_id, $woman_terms_ids ) ) {
            _e('Hello woman', 'woocommerce');
        }
    }
}

字符串
代码放在你的子主题的functions.php文件中(或插件中)。测试和工作。

pieyvz9o

pieyvz9o2#

您可以使用WordPress函数cat_is_ancestor_of()
查看文档:https://developer.wordpress.org/reference/functions/cat_is_ancestor_of/
基本上,你给它给予两样东西:你认为是父类别和你期望是子类别的东西。
无论层次结构有多深,它都将返回true。
这里有一个快速的例子,你可以让它工作:

$current_category = get_queried_object();
$man_category_id = get_cat_ID('Man');

// Check if the current category or its ancestors include the "Man" category
if (cat_is_ancestor_of($man_category_id, $current_category->term_id)) {
    echo "Display your content here";
}

字符串
只是提醒一下,我还没有测试过这段代码,所以请随意调整它以适应您的情况。

相关问题