自动从Woocommerce中的非促销产品中删除促销产品类别 [英] Auto remove Sale product category from not on sale products in Woocommerce
问题描述
在woocommerce中,我使用的是此答案线程中的代码,用于为正在销售的产品(因此具有有效的销售价格)分配销售产品类别。
In woocommerce I am using the code from this answer thread that assign a "Sale" product category to a product that is on sale (so with an active sale price).
当产品不再销售而没有成功时,我尝试删除销售产品类别。不再销售时,是否可以自动从销售类别中删除产品?
I have tried to remove "Sale" product category when the product is not on sale anymore without success. Is it possible to automatically remove products from the "Sale" category when they are not anymore on sale?
推荐答案
以下版本代码当产品不再销售时,将自动从销售类别中删除产品:
The following version code will automatically remove products from the "Sale" category when they are not anymore on sale:
add_action( 'save_post_product', 'update_product_set_sale_cat' );
function update_product_set_sale_cat( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
if ( ! current_user_can( 'edit_product', $post_id ) ) {
return $post_id;
}
if( get_post_status( $post_id ) == 'publish' && isset($_POST['_sale_price']) ) {
$sale_price = $_POST['_sale_price'];
if( $sale_price >= 0 && ! has_term( 'Sale', 'product_cat', $post_id ) ){
wp_set_object_terms($post_id, 'sale', 'product_cat', true );
} elseif ( $sale_price == '' && has_term( 'Sale', 'product_cat', $post_id ) ) {
wp_remove_object_terms( $post_id, 'sale', 'product_cat' );
}
}
}
代码进入function.php活动子主题(或活动主题)的文件。经过测试并有效。
Code goes in function.php file of your active child theme (or active theme). Tested and works.
相关:添加 Sale产品类别到在Woocommerce中销售的产品
这篇关于自动从Woocommerce中的非促销产品中删除促销产品类别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!