[英]How to Get the Current category ID in the product page in Woocommerce?
i would like to get the current category ID in the product page to show something in templates/single-product/add-to-cart/simple.php
in Woocommerce我想在产品页面中获取当前类别 ID,以在 Woocommerce 的
templates/single-product/add-to-cart/simple.php
中显示一些内容
If the category ID == 1 {//i'll show something}
if the category ID == 2 {//something else}
All of this in the " simple.php
"所有这些都在“
simple.php
”中
Thanks谢谢
Edit :编辑 :
<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' ) . ' ', '</span>' ); ?>
this code give the product name of the current product, if i can't get the ID, how could i get the string of the category name else ?此代码给出当前产品的产品名称,如果我无法获取 ID,我如何获取类别名称的字符串?
Use this code使用此代码
global $wp_query;
$terms_post = get_the_terms( $post->cat_ID , 'product_cat' );
foreach ($terms_post as $term_cat) {
$term_cat_id = $term_cat->term_id;
echo $term_cat_id;
}
Found some code online that might work as well (note: I have not tried it myself)在网上找到了一些可能也有效的代码(注意:我自己没有尝试过)
update link is dead, code is below just in case.更新链接已失效,代码在下方以防万一。
global $wp_query;
// get the query object
$cat_obj = $wp_query->get_queried_object();
print_r($cat_obj);
if($cat_obj) {
$category_name = $cat_obj->name;
$category_desc = $cat_obj->description;
$category_ID = $cat_obj->term_id;
echo $category_ID;
// with the `$category_ID`, proceed to your `if/else` statement.
if( $category_ID == 1){
echo 'Cat ID is 1';
}
if( $category_ID == 2){
echo 'Cat ID is 2';
}
}
Short way to get current category ID:获取当前类别 ID 的简单方法:
$terms = get_the_terms( $post->cat_ID , 'product_cat' );
echo $terms[key($terms)]->slug;
If you are in product page, first you need to get the product id like:如果您在产品页面,首先您需要获取产品 ID,如:
$product_id = $product->get_id();
then use this code:然后使用此代码:
$terms = get_the_terms( $product_id , 'product_cat' );
if ( !empty( $terms ) ) {
foreach ( $terms as $term ) {
echo $term->term_id;
}
}
You can use:您可以使用:
$product->get_category_ids()
This method has become available since WooCommerce 3, see the docs .此方法从 WooCommerce 3 开始可用, 请参阅文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.