簡體   English   中英

如何在 Woocommerce 的產品頁面中獲取當前類別 ID?

[英]How to Get the Current category ID in the product page 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}

所有這些都在“ simple.php ”中

謝謝

編輯 :

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', $cat_count, 'woocommerce' ) . ' ', '</span>' ); ?>

此代碼給出當前產品的產品名稱,如果我無法獲取 ID,我如何獲取類別名稱的字符串?

使用此代碼

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;
}

在網上找到了一些可能也有效的代碼(注意:我自己沒有嘗試過)

更新鏈接已失效,代碼在下方以防萬一。

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';
    }
}

獲取當前類別 ID 的簡單方法:

$terms = get_the_terms( $post->cat_ID , 'product_cat' );
echo $terms[key($terms)]->slug;

如果您在產品頁面,首先您需要獲取產品 ID,如:

$product_id = $product->get_id();

然后使用此代碼:

$terms = get_the_terms( $product_id , 'product_cat' );
            
if ( !empty( $terms ) ) {
    foreach ( $terms as $term ) {
        echo $term->term_id;
    }
}

您可以使用:

$product->get_category_ids()

此方法從 WooCommerce 3 開始可用, 請參閱文檔

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM