Jean R.
Jean R.

Reputation: 534

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.phpin Woocommerce

If the category ID == 1 {//i'll show something}

if the category ID == 2 {//something else}

All of this in the "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 ?

Upvotes: 3

Views: 49498

Answers (5)

Firefog
Firefog

Reputation: 3174

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

Upvotes: 10

bramchi
bramchi

Reputation: 800

You can use:

$product->get_category_ids()

This method has become available since WooCommerce 3, see the docs.

Upvotes: 2

sumon cse-sust
sumon cse-sust

Reputation: 454

If you are in product page, first you need to get the product id like:

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

Upvotes: 0

defro
defro

Reputation: 56

Short way to get current category ID:

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

Upvotes: 0

blurfus
blurfus

Reputation: 14031

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

Upvotes: 4

Related Questions