WooCommerce:以编程方式设定价格

时间:2015-05-26 12:22:53

标签: php wordpress woocommerce

我目前正在清空并在访问该网站时向用户购物车添加了一个产品 - 因为他们将只有一个产品(捐赠),如下所示:

function add_donation_to_cart() {
    global $woocommerce;
    $woocommerce->cart->empty_cart();
    $woocommerce->cart->add_to_cart('195', 1, null, null, null);
}

我使用自定义表单获取$_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语句有关,但即使产品价格设置为0,价格总是错误地设置为100。

任何帮助或见解都将不胜感激!

1 个答案:

答案 0 :(得分:1)

函数按预期工作,实际上if语句不正确。我检查了$_POST,因此$_SESSION存储的金额从未在点击结帐后重新分配为自定义价格(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;
    }
}

如果需要,请务必编辑您的付款模块!

相关问题