WooCommerce add to cart product with customized price

0

WooCommerce provides a hooks functionality using that we can change the product price programmatically. Many, Times we have to set the discount price for a specific user without touching the actual product price. WooCommerce allows us to change the product price without touching the actual product price. Let’s see, How we can WooCommerce add to cart product with a customized price.

WooCommerce add to cart product with a customized price

We can change the product price using the product ID. Let’s see, How we can change the product price with example. Just paste the below code into the functions.php file or plugin file.

add_filter('woocommerce_get_price','change_price', 10, 2);
add_filter('woocommerce_get_regular_price','change_price', 10, 2);
add_filter('woocommerce_get_sale_price','change_price', 10, 2);


function change_price($price, $productd){
     if($productd->id == '1'){
        $price = "150";
     }
     return $price;
}

First of all, Replace the product ID with actually product ID instead of 1. Then check the product price change without touching the product price. If you want to give a discount to a specific user then just add a condition on the user ID. Let’s see the example with user condition.

add_filter('woocommerce_get_price','change_price', 10, 2); add_filter('woocommerce_get_regular_price','change_price', 10, 2); add_filter('woocommerce_get_sale_price','change_price', 10, 2);

function change_price($price, $productd){ 
  $current_user_id = get_current_user_id();
  if( $current_user_id == 15 && $productd->id == 1){ 
    $price = "150";
  } 
  return $price;
}

Now, Product has changed only for 15 number user and remaining same for other users.

I hope this article useful for you. Please let us know if anything was missing or wrong by comment.

Share.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.