首页 > 解决方案 > 在商店图片下方添加 Woocommerce 类别

问题描述

我正在努力将产品类别添加到我网站上的商店图片下。我使用下面的代码让它工作,但类别之间没有空格。我在这里有点新手,所以想知道是否有人可以帮助我,我可以在每个类别列表之间添加一个逗号空格,这会很棒!提前致谢。

    add_action( 'woocommerce_after_shop_loop_item', 'after_shop_loop_item_title', 1 );

function after_shop_loop_item_title() {
    global $post;
    $terms = get_the_terms( $post->ID, 'videocategories' ); 
  $text = "<h3>Category: ";

    foreach ($terms as $term) {
        $text .= $term->name;
    }
    $text .= "</h3>";
    echo $text;

}

标签: phpwordpresswoocommercehook-woocommerce

解决方案


您可以使用 PHPimplode()函数。这将从数组中创建一个字符串,并使用您选择的分隔符将它们分开。

在下面的示例中,我首先创建了一个类别数组,然后将该implode()函数与该函数结合使用以打印由标签printf()包围的逗号分隔列表:h3

add_action( 'woocommerce_after_shop_loop_item', 'after_shop_loop_item_title', 10 );
function after_shop_loop_item_title() {

    global $post;
    $terms = get_the_terms( $post->ID, 'videocategories' ); 
    $product_cats = array();

    if ( !empty( $terms ) ) {
        // Get an array of the categories
        foreach ( $terms as $key => $term ) {
            $product_cats[] = sprintf( '<a href="%s">%s</a>', get_term_link( $term->slug, 'videocategories' ), $term->name );
        }
        // Convert product category array into comma separated string
        printf( '<h3>Category: %s</h3>', implode( ', ', $product_cats ) );
    }
}

推荐阅读