在商店图片下方添加Woocommerce类别 [英] Adding Woocommerce categories below the shop images

查看:29
本文介绍了在商店图片下方添加Woocommerce类别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力将产品类别添加到网站上的商店图片下方.我可以使用下面的代码来工作,但是类别之间没有空格.我在这里有点新手,所以想知道是否有人可以帮助我在哪里可以在每个类别列表之间添加逗号空格,这真是太好了!预先感谢.

I was working on adding the product categories to under the shop image on my site. I have it working using the code below, but the categories do not have spaces between them. I am a bit of a novice here so wondered if someone can help me where I could add a space of comma between each category listing that would be great! Thanks in advance.

    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;

}

推荐答案

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

You can use the PHP implode() function. This will create a string from an array and separate them with a separator of your choosing.

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

In the example below I first created an array of the categories and then used the implode() function in combination with the printf() function to print a comma separated list enclosed by h3 tags:

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 ) );
    }
}

这篇关于在商店图片下方添加Woocommerce类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆