Woocommerce 添加 类 到标签

Woocommerce add classes to tags

我想在 woocommerce 产品标签中添加 class。

这是我当前的代码:

<?php
    echo $product->get_tags( ', ', '<span class="tagged_as">' . _n( 'Tag:', 'Tags:', $tag_count, 'woocommerce' ) . ' ', '.</span>' );
?>

输出

<a rel="tag" href="">spicy</a>

我想要的

<a rel="tag" href="" class="spicy" title="spicy">spicy</a>

试试这个代码:

<?php
$tags = get_the_terms( $post->ID, 'product_tag' );

$html = '<div class="post_tags">';
foreach ( $tags as $tag ) {
    $tag_link = get_tag_link( $tag->term_id );
    $html .= "<a href='/product-tag/{$tag->term_id}' title='{$tag->name} Tag' class='{$tag->slug}'>";
    $html .= "{$tag->name}</a> ";
}
$html .= '</div>';
echo $html;
?>

我想,我知道问题出在哪里了。当页面上存在没有标签的产品时,foreach 在第一个参数中获取一个字符串。只需添加 if else 指令。我更正了链接代码。

    $tags = get_the_terms( $post->ID, 'product_tag' );
    if ($tags === false){
    }
    else{
        $html = '<div class="post_tags">';
        foreach ( $tags as $tag ) {
            $tag_link = get_tag_link( $tag->term_id );
            $html .= "<a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}'>";
            $html .= "{$tag->name}</a> ";
        }
        $html .= '</div>';
        echo $html;
    }