在商店图片下方添加Woocommerce类别

时间:2020-06-11 20:43:43

标签: php wordpress woocommerce hook-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;

}

1 个答案:

答案 0 :(得分:0)

您可以使用PHP implode()函数。这将从数组创建一个字符串,然后使用您选择的分隔符将它们分隔。

在下面的示例中,我首先创建了一个类别数组,然后将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 ) );
    }
}