Check a product category for a product in Woocommerce

女生的网名这么多〃 提交于 2021-02-05 08:16:06

问题


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.


回答1:


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:

  • Display the default discounted price and percentage on Woocommerce products
  • Check for Product Category in cart items with WooCommerce
  • And some others…


来源:https://stackoverflow.com/questions/54393944/check-a-product-category-for-a-product-in-woocommerce

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!