Auto remove Sale product category from not on sale products in Woocommerce

柔情痞子 提交于 2019-12-11 04:09:51

问题


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?


回答1:


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). Tested and works.

Related: Adding "Sale" product category to products that are on sale in Woocommerce



来源:https://stackoverflow.com/questions/52575108/auto-remove-sale-product-category-from-not-on-sale-products-in-woocommerce

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