显示 WooCommerce 当前产品类别或标签的短代码

问题描述 投票:0回答:1

我想制作两个短代码来显示 Woocommerce 产品。

简码1:

  • 显示 Woocommerce 当前产品标签。
  • 标签必须是链接。
  • 标签必须用 , 分隔,

简码2:

  • 显示 Woocommerce 当前产品类别
  • 标签必须是链接。
  • 标签必须用 , 分隔,

短代码应显示类别/链接,如下所示 enter image description here

我尝试过这个短代码,但显示的标签不是链接。 我希望将它们显示为链接。

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);
    }
}
php wordpress woocommerce shortcode taxonomy-terms
1个回答
0
投票

您可以使用以下简码来获取链接术语:

add_shortcode( 'wc_product_cat', 'get_linked_term_names_for_product' );
function get_linked_term_names_for_product( $atts ) {
    // Shortcode attribute (or argument)
    extract( shortcode_atts( array(
        'taxonomy'   => 'product_cat', // Product categories as default (Use 'product_tag' for product tags)
        'product_id' => get_the_id(), // current default product Iddefault)
    ), $atts, 'wc_product_cat' ) );
    
    $terms = (array) wp_get_post_terms( $product_id, $taxonomy );
    $linked_terms = array(); // Initializing
 
    if( empty($terms) ) return; // Exit
    
    // Loop through each term
    foreach ( $terms as $term ) {
        $term_link = get_term_link($term); // get term link
        $linked_terms[] = $term_link ? sprintf( '<a href="%s">%s</a>', $term_link, $term->name ) : $term->name;
    }

    return implode(', ', $linked_terms);
}

代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。

使用

  1. 对于产品类别:
    [wc_product_cat]
  2. 对于产品标签:
    [wc_product_cat taxonomy="product_tag"]
  3. 对于其他分类法,使用分类法简码参数定义分类法
© www.soinside.com 2019 - 2024. All rights reserved.