2015-05-26 58 views
1

我目前排空,并增加了产品的用户购物车访问该网站的时候 - 因为他们将永远只有一个单品(捐赠),像这样: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语句,但价格总是错误地设置为100即使产品价格设置为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; 
    } 
} 

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