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();
}
}
我正在尝试根据当时的价格自动标记产品,但无法做到这一点。可以这样做吗?
以下简化和修订的代码版本还将处理可变产品(基于变化最高价格),根据范围的产品价格添加产品标签:
789
术语 ID,456
术语 ID,123
术语 ID。尝试这个替换代码:
add_action( 'woocommerce_new_product', 'auto_add_product_tag_based_on_price', 10, 2 );
add_action( 'woocommerce_update_product', 'auto_add_product_tag_based_on_price', 10, 2 );
function auto_add_product_tag_based_on_price( $product_id, $product ) {
// Handle all product types price
$price = $product->is_type('variable') ? $product->get_variation_price('max') : $product->get_price();
if ( $price >= 200 ) {
$term_id = 66; // 789
} elseif ( $price >= 100 ) {
$term_id = 65; // 456
} else {
$term_id = 64; // 123
}
if ( ! has_term($term_id, 'product_tag', $product_id) ) {
wp_set_post_terms($product_id, [$term_id], 'product_tag');
}
}
代码位于子主题的functions.php 文件中(或插件中)。已测试并有效。