Reputation: 1
I'm doing an eCommerce with woocommerce and I must do the following:
Modify the price of all products through functions.php. The function I created works for all of the site's prices, except for the values of the cart.
I'm putting the function below:
function woo_change_price($price, $product) {
global $woocommerce, $product;
$post_id = $product->id;
$regular_price = get_post_meta( $post_id, '_regular_price', true);
$sale_price = get_post_meta( $post_id, '_sale_price', true);
$cupom_value = ($regular_price - $sale_price) / 10;
$price = $cupom_value;
return $price;
}
add_filter('woocommerce_get_price', 'woo_change_price', 99);
add_filter('woocommerce_get_sale_price', 'woo_change_price', 99);
add_filter('woocommerce_order_amount_item_subtotal', 'woo_change_price', 99);
See that what I need is to get the regular price and the price on sale of the product and make a basic account of mathematics, subtracting the two and dividing by 10. The result I set as the new price of the product.
This function works perfectly in all site, except in the cart. When I see the cart, all the values are set to 0 (the prices, the total, the subtotals etc).
I found why it is happening this error, but I don't now how to fix it. The problem is: the $product->id is not identified by the cart and then returns 0.
How can I fix that?
Thank you!
Upvotes: 0
Views: 1934
Reputation: 664
Not sure if this is what you're looking for, but you can use something like this to modify the price of items once they are added to the cart.
add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );
function add_custom_price( $cart_object ) {
foreach ( $cart_object->cart_contents as $key => $value ) {
$post_id = $value['product_id'];
$regular_price = get_post_meta( $post_id, '_regular_price', true);
$sale_price = get_post_meta( $post_id, '_sale_price', true);
$cupom_value = ($regular_price - $sale_price) / 10;
$price = $cupom_value;
$value['data']->price = $price;
}
}
This affects the cart directly. The prices of items themselves won't be changed, but the price of the items within the cart will be updated to reflect the value you've defined.
Upvotes: 0