产品类别描述简码

时间:2020-09-26 17:21:53

标签: wordpress woocommerce

我在这里有此代码以获取简码

function showtax_func( $atts ) {
    $a = shortcode_atts( array(
        'tax' => '',
    ), $atts );
    
    $termname = get_the_terms(get_the_ID(),$a['tax'])[0]->name;
    return $termname;

}
add_shortcode( 'show_tax', 'showtax_func' );

如何将woocommerce的product_cat-> ID或Slug作为参数传递?

这段代码可以在single.php模板中获取所有描述,

$args = array( 'taxonomy' => 'product_cat' );
$terms = get_terms('product_cat', $args);

$count = count($terms); 
if ($count > 0) {
   foreach ($terms as $term) {
      echo $term->description;
    }
}

我想根据需要在帖子中的简码中为单个帖子添加单个产品类别描述。

例如:[product_cat =“ 500”]或slug ...,我将在帖子中获得产品类别ID 500的描述。

1 个答案:

答案 0 :(得分:1)

如果我完全理解您的问题...

要创建一个通过ID显示产品目录的简码,您需要简码名称product_cat和变量id

然后您可以执行此操作。

function showtax_func( $atts ) {
    $a = shortcode_atts( array(
        'id' => '',
    ), $atts );
    
    // Get the term object by ID passed from shortcode
    $term = get_term_by('id', $a['id'], 'product_cat');
    
    return $term->description; // or anything from the WP_Term object.

}
add_shortcode( 'product-cat', 'showtax_func' );

用途为[product-cat id="123"]-返回类别说明