【问题标题】:Adding Woocommerce categories below the shop images在商店图片下方添加 Woocommerce 类别
【发布时间】:2020-09-29 01:50:47
【问题描述】:

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

    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 wordpress woocommerce hook-woocommerce


    【解决方案1】:

    您可以使用 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 ) );
        }
    }
    

    【讨论】:

    • 谢谢你做得很好!!祝您有美好的一天,非常感谢!
    • 没问题,很高兴它有帮助。
    • 您好!是否也可以轻松地在上述代码中添加指向该类别的链接,以便它可以点击并向您显示所有附加该类别的产品?提前致谢!
    • 当然,请参阅更新的答案。 (未经测试,但应该可以工作。)
    • 没问题。如果您愿意,也可以为答案投票。
    猜你喜欢
    • 2015-12-19
    • 1970-01-01
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-02
    • 2019-08-19
    相关资源
    最近更新 更多