1

I'm writing a function in functions.php. I am working with woocommerce and trying to get posts with the same cat name of product_cat on single product pages. My idea is using the cat name of woocommerce cat and get_cat_ID() to get the category ID, then use WP_query to get the posts. However, get_cat_ID() always returns 0 (I event create a category called 'test', but still). Tried to google the problem but no solution. get_cat_ID() seems to be really straightforward so I am really not sure what went wrong. It would be great if anyone can let me know what would be the possible reason.

To sum up my problem: I have a product_cat named 'test'. Now I want to get the ID of the category with the same name 'test'.

Here's the code:

$cate_object = get_the_terms( $post->ID, 'product_cat' );
foreach( $cate_object as $cate ){
    // get cat id by tax name
    $thisCatName = $cate->name;
    $thisCatID = get_cat_ID($thisCatName);
    if($thisCat !== null && $thisCat != 0)
        $cat_array[] = $thisCatID;
}

Thanks!

2
  • 1
    did you mean to check $thisCatID in this line ` if($thisCat !== null && $thisCat != 0)` ?
    – Michael
    Commented Apr 6, 2020 at 3:02
  • Yes. If the product_cat name finds a corresponding cat, it will be added to $cat_array.
    – Wei
    Commented Apr 11, 2020 at 15:39

2 Answers 2

2

get_cat_ID gets the ID of a category based on the name. "Category" is a specific taxonomy named category. You're trying to get the ID of a Product Category (product_cat). You cannot use get_cat_ID() to get the ID of a custom taxonomy.

To do that you need to use get_term_by():

$product_cat = get_term_by( 'name', $cat_name, 'product_cat' );

if ( $product_cat ) {
    $thisCatID = $product_cat->term_id;
}

But, based on your code, you don't need to be finding the ID. You already have it:

$cate_object = get_the_terms( $post->ID, 'product_cat' );
foreach( $cate_object as $cate ){
    $thisCatID = $cate->term_id; // This is the ID.

    $cat_array[] = $thisCatID;
}
1
  • Hey Jacob, thanks for your reply. Maybe I didn't address my question clearly: I have a product_cat named, say, 'test'. Now I am trying to get the category id that has the same name 'test'. I have edited my post to clarify my question.
    – Wei
    Commented Apr 6, 2020 at 1:33
1

For people who has the same problem: I think the problem is caused by Polylang. I checked my category list on dashboard, and realized that the category I failed to get with get_cat_ID() doesn't belong to any language (which is weird). I created a test category and give assign a language to it, then get_cat_ID() works!

Thanks to people who tried to help out!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.