简体   繁体   English

自动从 Woocommerce 中的非销售产品中删除销售产品类别

[英]Auto remove Sale product category from not on sale products in 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) .在 woocommerce 中,我使用此答案线程的代码将“销售”产品类别分配给正在销售的产品(因此具有有效的销售价格)

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' );
        }
    }
}

Code goes in function.php file of your active child theme (or active theme).代码位于活动子主题(或活动主题)的 function.php 文件中。 Tested and works.测试和工作。

Related: Adding "Sale" product category to products that are on sale in Woocommerce相关: 将“销售”产品类别添加到 Woocommerce 中销售的产品

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM