1

I want to check the category of a WooCommerce product post right after it's created(or updated) and then run some more code based on the category.

To check post on creation/update I used save_post and for category has_category. Something goes wrong with has_category and it doesn't return anything at all. I tried replacing $post_id with $post and $post->ID as suggested in other issues but that didn't change anything.

function doFruitStuff($post_id){ // Function in functions.php
    $fruits = 'fruits';
    if(has_category($fruits, $post_id)){
    echo "<script type='text/javascript'>alert('has the category');</script>";
}else{
    echo "<script type='text/javascript'>alert('doesnt have the category');</script>";
}}
add_action('save_post', 'doFruitStuff');

Am I using has_category incorrectly or WooCommerce product categories work differently?

I'm used to debugging in javascript alerts, sorry about that. Any help greatly appreciated.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
Zae
  • 47
  • 9

1 Answers1

2

You can't use has_category() Wordpress function to check Woocommerce product categories.

Note: Product category is a custom taxonomy used by Woocommerce.

So instead you will need to use has_term() with Woocommerce product categories this way:

add_action('save_post', 'do_fruit_stuff');
function do_fruit_stuff( $post_id ){
    $terms = array('fruits');
    if( has_term( $terms, 'product_cat', $post_id ) ){
        echo "<script type='text/javascript'>alert('has the product category');</script>";
    }else{
        echo "<script type='text/javascript'>alert('doesnt have the product category');</script>";
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

Note: The custom taxonomy used for Woocommerce product categories is "product_cat".


Related threads:

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • Needless to say but that works perfectly. Thank you so so so much! :) – Zae Jan 28 '19 at 01:12
  • 1
    As product categories are hierarchical you can also use [this kind of custom conditional function](https://stackoverflow.com/a/54048257/3730754) that will handle the parent terms. – LoicTheAztec Jan 28 '19 at 01:18
  • 1
    I didn't even realize I now gained the right to upvote. Thank you for pointing that out too! :) – Zae Jan 28 '19 at 01:19