在Woocommerce中检查产品类别的产品 [英] Check a product category for a product in Woocommerce
问题描述
我想在创建(或更新)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.
要检查有关创建/更新的帖子,我使用了 save_post
,并使用了类别 has_category
. has_category
出了点问题,它根本不返回任何内容.我尝试按照其他问题中的建议用 $ post
和 $ post-> ID
替换 $ post_id
,但这并没有改变.
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');
我使用 has_category
的方式有误还是WooCommerce产品类别的工作方式不同?
Am I using has_category
incorrectly or WooCommerce product categories work differently?
我曾经在javascript警报中调试过,对此感到抱歉.任何帮助都将不胜感激.
I'm used to debugging in javascript alerts, sorry about that. Any help greatly appreciated.
推荐答案
您不能使用
has_category()
Wordpress函数检查Woocommerce产品类别.
You can't use
has_category()
Wordpress function to check Woocommerce product categories.
注意:产品类别是Woocommerce使用的自定义分类法.
Note: Product category is a custom taxonomy used by Woocommerce.
因此,您需要使用 has_term()代码>
与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>";
}
}
代码进入您的活动子主题(或活动主题)的function.php文件中.经过测试,可以正常工作.
Code goes in function.php file of your active child theme (or active theme). Tested and works.
注意:用于Woocommerce产品类别的自定义分类法是" product_cat
".
Note: The custom taxonomy used for Woocommerce product categories is "product_cat
".
相关线程:
这篇关于在Woocommerce中检查产品类别的产品的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!