4

I have added number of products using add_to_cart($product_id) function through a template using following code in WooCommerce Wordpress.

global $woocommerce;
$id_arr = $_POST['up_product_chk'];
$i = 0;
for($i; $i<=count($id_arr); $i++){
   $ids = $id_arr[$i];
   $woocommerce->cart->add_to_cart($ids);  
}
wp_redirect(site_url().'/cart/');

Now I wish to add custom price for each product through this template. As now price in cart is same as in database but I want to add my custom price through this point. Can someone help me to do the same. Thanks

Pramod
  • 43
  • 1
  • 4

1 Answers1

7

using this hook you can set your custom price. write this code in functions.php 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;
}

This way you can set a custom price in woocommerce without effecting the database.

fore more detail please read this article TryVary.com

I hope this is useful for you.

Renish Khunt
  • 5,620
  • 18
  • 55
  • 92
  • Yes, with the help of above code I can set my custom price to any of the product but rest of the products price turns to 0 (Zero). As there are hundread of products. Its not possible to assign price to each of the product. – Pramod May 30 '14 at 06:59
  • rest of the product you can return '0'. when you return '0' this product price is free.and also you create meta box for your custom price and using product id you can get your custom price in this function. now check the custom price is not null then return your custom price other wise return $price it is original product price. – Renish Khunt May 30 '14 at 07:09
  • Okay, upto this point everything looks good. Price defined to product using above function reflect in complete site. But in my case I am providing them discount in offer pop up when they click on checkout button. So here is an issue, there would be regular price in the cart if product is added through single product page but if product is added through offer pop up then discount price should be in cart. This is tricky part. – Pramod May 30 '14 at 08:05
  • You need to return `$price` no matter what, otherwise all products (Excepting ID=1) will have a null price. – helgatheviking Feb 06 '15 at 14:55