【问题标题】:Show WooCommerce product tag name set for a product with a shortcode使用简码显示为产品设置的 WooCommerce 产品标签名称
【发布时间】:2021-01-12 20:37:07
【问题描述】:

正如标题所说,我正在寻找可以用来显示特定产品标签的简码。 我所有的产品都只设置了一个产品标签。

例如,如果 ID 为 1250 的产品带有标签“Horse”,我需要放置一个指定产品 ID 的短代码并显示您各自的标签的方法。在示例中,短代码应在屏幕上显示单词“Horse”

特意修改如下代码来实现:

$terms = wp_get_post_terms( get_the_id(), 'product_tag' );

if( count($terms) > 0 ){
foreach($terms as $term){
$term_id = $term->term_id; // Product tag Id
$term_name = $term->name; // Product tag Name
$term_slug = $term->slug; // Product tag slug
$term_link = get_term_link( $term, 'product_tag' );

$output[] = '.$term_name.';
}

$output = implode( ', ', $output );

echo $output;
}

但我没有足够的知识来实现​​它

感谢任何帮助。

【问题讨论】:

    标签: php wordpress woocommerce shortcode taxonomy-terms


    【解决方案1】:

    如果您为每个产品只设置了一个产品标签,则以下简码函数将输出为当前产品设置的产品标签术语名称(或一串逗号分隔的术语名称,当为一个产品设置多个术语时) )。它也适用于定义的产品 ID 作为短代码中的参数(参见用法示例)

    功能代码:

    add_shortcode( 'wc_product_tag', 'get_tag_term_name_for_product_id' );
    function get_tag_term_name_for_product_id( $atts ) {
        // Shortcode attribute (or argument)
        extract( shortcode_atts( array(
            'taxonomy'   => 'product_tag', // The WooCommerce "product tag" taxonomy (as default)
            'product_id' => get_the_id(), // The current product Id (as default)
        ), $atts, 'wc_product_tag' ) );
        
        $term_names = (array) wp_get_post_terms( $product_id, $taxonomy, array('fields' => 'names') );
     
        if( ! empty($term_names) ){
            // return a term name or multiple term names (in a coma separated string)
            return implode(', ', $term_names);
        }
    }
    

    代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试并且可以工作。

    用法示例:

    • 对于当前产品:[wc_product_tag]
      或在 php 中:echo do_shortcode('[wc_product_tag]');
    • 对于定义的产品 ID:[wc_product_tag product_id="37"]
      或在 php 中:echo do_shortcode('[wc_product_tag product_id="37"]');

    这也适用于任何产品自定义分类,如 WooCommerce 产品类别……

    要显示为您需要替换的产品设置的 WooCommerce 产品类别术语名称

            'taxonomy'   => 'product_tag', // The WooCommerce "Product Tag" taxonomy (as default)
    

    通过以下行:

            'taxonomy'   => 'product_cat', // The WooCommerce "Product Category" taxonomy (as default)
    

    【讨论】:

    • 太棒了!我今天学了些新东西。非常感谢!
    • 此代码无效
    猜你喜欢
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多