在 Woocommerce 产品标题中显示多个类别

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

我需要在单个产品标题中显示所有关联的产品类别。例如,销售分期发行的唱片,该唱片有两个不同的艺术家类别相关联。

根据此答案,以下代码将在产品标题中显示单个产品类别术语。

function category_single_product(){

    $terms = get_the_terms( get_the_ID(), 'product_cat' );
    
    foreach ($terms as $term) ?>
    
        <b><span itemprop="name" class="product_category_title"><span><?php echo $term->name; ?></span></span></b>

<?php }

add_action( 'woocommerce_before_shop_loop_item_title', 'category_single_product', 25 );

但它没有在单个产品标题中显示所有关联的产品类别。 如何显示多个类别术语?

php wordpress woocommerce product taxonomy-terms
1个回答
0
投票

要显示与产品关联的所有产品类别,请尝试以下操作:

add_action( 'woocommerce_before_shop_loop_item_title', 'category_single_product', 25 );
function category_single_product(){
    // Get product category terms for the current product
    $terms = get_the_terms( get_the_ID(), 'product_cat' );

    // Check if there are product categories assigned to the product
    if ( $terms && ! is_wp_error( $terms ) ) {
        // Get only an array of term names
        $term_names = array_column( $terms, 'name' ); 

        // Output the comma separated string of term names
        printf('<b><span itemprop="name" class="product_category_title"><span>%s</span></span></b>', implode(', ', $term_names) );
    }
}

应该有效

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