I am currently emptying and added a product to the users cart when visiting the site - as they will ever only have a single product (a donation), like so:
function add_donation_to_cart() {
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart('195', 1, null, null, null);
}
I use a custom form to get the $_POST
information - the amount is posted to the donations page, effectively the users cart, which already has a product in it. The custom amount is used in the function below to alter the price. The price displays correctly in the cart, on the checkout page as well as on the redirected payment gateway (within the redirected page itself).
However, as soon as you are redirected, woocommerce creates an order and it is marks it as 'processing'. The amount displayed on the order is incorrect.
The function I have used to change the price is displayed below:
add_action('woocommerce_before_calculate_totals', 'add_custom_total_price');
function add_custom_total_price($cart_object)
{
session_start();
global $woocommerce;
$custom_price = 100;
if($_POST)
{
if(!empty($_POST['totalValue']))
{
$theVariable = str_replace(' ', '', $_POST['totalValue']);
if(is_numeric($theVariable))
{
$custom_price = $theVariable;
$_SESSION['customDonationValue'] = $custom_price;
}
else
{
$custom_price = 100;
}
}
}
else if(!empty($_SESSION['customDonationValue']))
{
$custom_price = $_SESSION['customDonationValue'];
}
else
{
$custom_price = 100;
}
var_dump($_SESSION['customDonationValue']);
foreach ( $cart_object->cart_contents as $key => $value )
{
$value['data']->price = $custom_price;
}
}
Now I'm not entirely sure if it has something to do with my if statement, but the price is always incorrectly set to 100 even though the products price is set to 0.
Any help or insight would be appreciated!