skip to Main Content
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


  1. 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:

    • with a price up to $200, the product will be tagged with 789 term ID,
    • with a price between $100 and $200, the product will be tagged with 456 term ID,
    • with a price lower than $100, the product will be tagged with 123 term ID.

    Try this replacement code:

    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 = 789;
        } elseif ( $price >= 100 ) {
            $term_id = 456;
        } else {
            $term_id = 123;
        }
    
        if ( ! has_term($term_id, 'product_tag', $product_id) ) {
            wp_set_post_terms($product_id, [$term_id], 'product_tag'); 
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Login or Signup to reply.
  2. Is there a way to apply this only to products from a specific category?

    Thanks

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search