[英]Check a product category for a product in Woocommerce
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. 我想在创建(或更新)WooCommerce产品后立即检查其类别,然后根据该类别运行更多代码。
To check post on creation/update I used save_post
and for category has_category
. 要检查创建/更新后我用
save_post
和第一类has_category
。 Something goes wrong with has_category
and it doesn't return anything at all. has_category
,它根本不返回任何东西。 I tried replacing $post_id
with $post
and $post->ID
as suggested in other issues but that didn't change anything. 我尝试按照其他问题中的建议用
$post
和$post->ID
替换$post_id
,但这没有任何改变。
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? 我使用
has_category
误还是WooCommerce产品类别的工作方式不同?
I'm used to debugging in javascript alerts, sorry about that. 我曾经在javascript警报中调试过,对此感到抱歉。 Any help greatly appreciated.
任何帮助,不胜感激。
You can't use
has_category()
Wordpress function to check Woocommerce product categories .您不能使用
has_category()
Wordpress函数检查Woocommerce产品类别 。
Note: Product category is a custom taxonomy used by Woocommerce. 注意:产品类别是Woocommerce使用的自定义分类法。
So instead you will need to use has_term()
with Woocommerce product categories this way: 因此,您需要通过以下方式将
has_term()
与Woocommerce产品类别一起使用:
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). 代码进入您的活动子主题(或活动主题)的function.php文件中。 Tested and works.
经过测试和工作。
Note: The custom taxonomy used for Woocommerce product categories is " product_cat
". 注意:用于Woocommerce产品类别的自定义分类法是“
product_cat
”。
Related threads: 相关主题:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.