1

我想为我的 wp+woocommerce 网站创建一个简码,它将显示当前产品类别的名称。我通过获取请求从我的 url 中获取类别 ID - 这是一项专业。它看起来像:

function this_product_category_name() {
$cat_id = (int) str_replace('-product_cat', '', $_GET['really_curr_tax']);
// here must be a string to get the $cat_name from $cat_id;
echo $cat_name;
}

add_shortcode( 'this_product_category_name', 'this_product_category_name' );

有什么解决办法?

4

2 回答 2

0

Use get_term_by().

function this_product_category_name() {
    $cat_id = (int) str_replace('-product_cat', '', $_GET['really_curr_tax']);
    $product_cat = get_term_by( 'id', $cat_id, 'product_cat' );
    echo $product_cat->name;
}
add_shortcode( 'this_product_category_name', 'this_product_category_name' );

USEFUL LINKS

于 2021-05-02T08:44:09.343 回答
0

既然您在product category页面上,那么您可以使用get_queried_object,然后从该对象中您可以获得name如下信息:

$cat = get_queried_object();

echo $cat->name;

//or if you want to get its id 

echo $cat->term_id;

//if you want to see the object and what's in it then you could use print_r()

print_r($cat);

让我知道这是否是你要找的。

所以你的代码会是这样的:

function this_product_category_name() 
{

  $cat = get_queried_object();

  echo $cat->name;

}

add_shortcode( 'this_product_category_name', 'this_product_category_name' );
于 2021-05-01T23:44:12.737 回答