Adding the Sales category to products that are sold using the save_post hook

As part of the WooCommerce site, I want to have a sale page that lists the elements of the sale (pagination and filtering). I think the best way to do this is to have a "Sales" category, which is automatically added to any messages that are part of the sale (since category pages allow you to automatically filter and paginate).

I have this code so far to programmatically add a sale category to products while saving them:

function update_test( $product) { wp_set_object_terms($product, 'sale', 'product_cat', true ); } add_action( 'save_post', 'update_test', 1, 2);` 

However, I want this to happen only if the product is sold (it has a sale price), so saving messages that are not for sale does not add a sale category. I tried a few different things, but no luck. I tried this, but it did not work:

 function update_test( $product ) { if($product->is_on_sale()){ wp_set_object_terms($product, 'sale', 'product_cat', true ); } } add_action( 'save_post', 'update_test', 1, 2);` 

but it just made my site freeze when saved.

Any ideas?

Andy

+5
source share
1 answer

- Updated -

save_post is a WordPress trap that works with the $post_id argument and is designed for all types of posts. First of all, you need to configure product custom WooCommerce post_type in state (and publish post_status ).

Also, since this is not a post object, you cannot use the is_on_sale() method. But you can use the get_post_meta() function to check if the selling price is set in the product.

Here is a fully functional and tested code:

 function update_product_set_sale_cat( $post_id ) { // Get the post object $post = get_post( $post_id ); if($post->post_type == 'product' && $post->post_status == 'publish') { $sale_price = get_post_meta($post_id, '_sale_price', true); if(!empty($sale_price) || $sale_price > 0) wp_set_object_terms($post_id, 'sale', 'product_cat', true ); } } add_action( 'save_post', 'update_product_set_sale_cat', 1, 2); 

The code goes in the function.php file of your active child theme (or theme). Or also in any php file plugins.

+2
source

Source: https://habr.com/ru/post/1260793/


All Articles