Php WooCommerce:以编程方式设置价格
我目前正在清空并在访问网站时将一个产品添加到用户购物车中,因为他们将永远只有一个产品(捐赠),如下所示:Php WooCommerce:以编程方式设置价格,php,wordpress,woocommerce,Php,Wordpress,Woocommerce,我目前正在清空并在访问网站时将一个产品添加到用户购物车中,因为他们将永远只有一个产品(捐赠),如下所示: function add_donation_to_cart() { global $woocommerce; $woocommerce->cart->empty_cart(); $woocommerce->cart->add_to_cart('195', 1, null, null, null); } 我使用自定义表单获取$\u POST信息
function add_donation_to_cart() {
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart('195', 1, null, null, null);
}
我使用自定义表单获取$\u POST
信息-金额将发布到捐赠页面,实际上是用户购物车,该购物车中已经有产品。自定义金额在下面的函数中用于更改价格。价格正确显示在购物车、结帐页面以及重定向支付网关(在重定向页面本身内)上
但是,一旦您被重定向,woocommerce就会创建一个订单,并将其标记为“正在处理”。订单上显示的金额不正确
我用于更改价格的功能如下所示:
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;
}
}
现在我不完全确定它是否与我的if语句有关,但是价格总是错误地设置为100,即使产品价格设置为0
任何帮助或见解都将不胜感激 函数按预期工作,事实上if语句不正确。我检查了
$\u POST
,它是存在的,因此在单击结帐后,$\u会话
存储的金额从未被重新分配为自定义价格(在本例中,该POST会导致问题)。我把它改成这样:
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(!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 = 50;
}
foreach ( $cart_object->cart_contents as $key => $value ) {
$value['data']->price = $custom_price;
}
}
如果需要,请确保编辑您的支付模块