Adding “Sale” product category to products that are on sale in Woocommerce

后端 未结 1 2008
盖世英雄少女心
盖世英雄少女心 2021-01-05 02:51

As part of a WooCommerce site I want to have a sale page that lists sale items (with pagination and filtering). I think the best way to do this is to have a \'Sale\' categor

相关标签:
1条回答
  • 2021-01-05 03:35

    Updated 2 (October 2018)

    save_post is a WordPress hook that works with $post_id argument and target all kind of posts. You need to target product custom WooCommerce post_type first in a condition (and publish post_status).

    Also as it's not a post object you can't use is_on_sale() method with it. But you can use get_post_meta() function to check if the sale price is set in the product.

    Here is the fully functional and tested code (for simple products only):

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

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

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

    0 讨论(0)
提交回复
热议问题