'Adding "Sale" product category to products that are on sale in Woocommerce
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' category that is added automatically to any posts that are part of the sale (as category pages allow for filtering and pagination automatically.
I have this code so far to programatically add the sale category to products when you save them:
function update_test( $product) {
wp_set_object_terms($product, 'sale', 'product_cat', true );
}
add_action( 'save_post', 'update_test', 1, 2);`
However, I only want this to happen if a product is on sale (i.e has sale price set) so that saving posts that are not on sale does not add the sale category. I have tried several different things, but have had no luck. I tried this, but it didnt 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 this just made my site freeze on save.
Any ideas?
Andy
Solution 1:[1]
I think a more convenient way of doing this, that also works on variable products, would be adding the following in child theme's function.php (or via a plugin, etc):
add_action( 'woocommerce_update_product', 'update_product_set_sale_cat', 10, 2 );
function update_product_set_sale_cat( $product_id, $product ) {
if ( $product->is_on_sale() ) {
wp_add_object_terms($product_id, "sale", 'product_cat');
} else { // this will also remove the sale category when the product in no longer on sale
wp_remove_object_terms($product_id, "sale", 'product_cat');
}
}
It uses the woocommerce_update_product hook which runs whenever a product is updated/created in the database.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | LyK |
