【问题标题】:Dynamically remove cart fees Woocommerce动态删除购物车费用 Woocommerce
【发布时间】:2018-05-08 16:27:10
【问题描述】:

我有一个使用 Woocommerce 插件的 WordPress 商店。我目前可以使用分配给woocommerce_cart_calculate_fees 挂钩的$woocommerce->cart->add_fee() 函数在结帐时动态添加费用。但是,我也希望能够在结帐时取消费用,但我还没有成功。我正在尝试通过 AJAX 触发 PHP 函数,然后使用 this method 清除费用。

当我从 clearfees() 函数中简单地回显“成功”时,AJAX 调用成功完成。但是,当我尝试调用 $WC()->cart->remove_all_fees() AJAX 失败并出现 500 错误。

从 Javascript 中移除费用 AJAX 调用

function clear_fees() {
  $.ajax({
  type: 'GET',
  url: entrada_params.admin_ajax_url,
  data: { action : 'clear_fees' }
  }).done( function( data ) {
    console.log(data);
  } )
  .fail( function( jqXHR, textStatus, errorThrown ) { // HTTP Error
    console.error( errorThrown );
  } );
}

我主题的functions.php中的clearfees函数

function clearfees() {

  $WC()->cart->remove_all_fees();
  wp_die();

}

// creating Ajax call for WordPress
add_action('wp_ajax_clear_fees', 'clearfees');
add_action('wp_ajax_nopriv_clear_fees', 'clearfees');

在我的搜索中,我在实践中发现关于 remove_all_fees() 函数的信息非常少,但如果我能让它工作,它似乎是合乎逻辑的解决方案。

【问题讨论】:

  • 大多数时候,费用是在特定的钩子函数中设置的......所以你不能这样删除它们......最好在添加费用的钩子中处理一个条件,这是最当时woocommerce_cart_calculate_fees ...你可以使用WC_Sessions来设置或删除费用......所以在你的php ajax函数中你将设置一个会话值,这将使woocommerce_cart_calculate_fees中的费用无效
  • @LoicTheAztec 但是那样它就不会是动态的。
  • @needle 不应该是WC()->cart->remove_all_fees();而不是$WC()->cart->remove_all_fees()吗?
  • 如果您想获得帮助,请在您的问题中添加您用于设置动态费用的完整代码,并解释上下文...

标签: ajax wordpress woocommerce


【解决方案1】:

我这样做是因为我在 function.php 中申请费用

add_action( 'woocommerce_cart_calculate_fees', 'custom_fee_based_on_cart_total', 10, 1 );
function custom_fee_based_on_cart_total( $cart_object ) {
    if(isset($_GET['implementation'])){
        $charges = (int)$_GET['charges'];
        $cart_total = (int)$cart_object->cart_contents_total;
        $fees = $cart_total + $charges;

        $applyfee = $_SESSION['applyfee'] ? $_SESSION['applyfee'] : 'true';
        if($applyfee == 'true'){
            $cart_object->add_fee( __( "Implementation Charges", "woocommerce" ), $charges, false );
        }else{
            $charges = 0;
            $cart_object->add_fee( __( "Implementation Charges", "woocommerce" ), $charges, false );
        }
    }
}

如果我选择移除费用选项

function clearfees() {

    $_SESSION['applyfee'] = 'false';
}
// creating Ajax call for WordPress
add_action('wp_ajax_clear_fees', 'clearfees');
add_action('wp_ajax_nopriv_clear_fees', 'clearfees');

当我得到成功响应时,最后刷新购物车页面。

【讨论】:

  • 虽然此代码可能会回答问题,但提供有关其解决问题的方式和/或原因的附加上下文将提高​​答案的长期价值。Read this
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-15
  • 2019-07-27
  • 2021-05-09
  • 2017-01-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多