add_action( 'woocommerce_update_product', 'auto_tag_product_by_price', 10, 1 );
function auto_tag_product_by_price( $product_id ) {
$product = wc_get_product( $product_id );
$price = $product->get_price();
// Define your price ranges and corresponding tag IDs here
$price_ranges = array(
'budget' => array( 'min' => 0, 'max' => 100, 'tag_id' => 123 ), // Replace 123 with your tag ID
'mid-range' => array( 'min' => 101, 'max' => 200, 'tag_id' => 456 ), // Replace 456 with your tag ID
'premium' => array( 'min' => 201, 'max' => 9999, 'tag_id' => 789 ), // Replace 789 with your tag ID
);
$assigned_tag = null;
foreach ( $price_ranges as $tag_name => $range ) {
if ( $price >= $range['min'] && $price <= $range['max'] ) {
$assigned_tag = $range['tag_id'];
break;
}
}
if ( $assigned_tag ) {
$product->set_tag_ids( array( $assigned_tag ) );
$product->save();
}
}
I am trying to automaticlly tagging products according to their prices at that moment but couldnt manage to do it. Is it possible to do this?
2
Answers
The following simplified and revised code version, will also handle variable products (based on the variation max price), adding a product tag based on the product price by ranges:
789
term ID,456
term ID,123
term ID.Try this replacement code:
Code goes in functions.php file of your child theme (or in a plugin). Tested and works.
Is there a way to apply this only to products from a specific category?
Thanks