【问题标题】:Add cart fee from a variable (customer balance) in woocommerce从 woocommerce 中的变量(客户余额)添加购物车费用
【发布时间】:2020-08-15 20:04:56
【问题描述】:

我正在尝试根据用户帐户余额在结帐时添加费用(折扣)。我们最终在几乎每个订单中都会退款,并且创建优惠券非常乏味。我创建了一个自定义用户字段,我可以在其中快速将退款金额设置为信用值,然后在结帐时应用以下订单。

到目前为止,除了费用在结帐加载时出现然后再次消失之外,一切正常。如果我设置一个静态金额,它会起作用,但是从变量设置费用时,我会得到上述行为。

添加用户自定义字段

add_action( 'show_user_profile', 'extra_user_profile_fields' );
add_action( 'edit_user_profile', 'extra_user_profile_fields' );

function extra_user_profile_fields( $user ) { ?>
    <h3><?php _e("FoodBox Info", "blank"); ?></h3>
    <table class="form-table">
    <tr>
    <th><label for="account-balance"><?php _e("Account Balance"); ?></label></th>
        <td>
            <input type="number" name="account-balance" id="account-balance" value="<?php echo esc_attr( get_the_author_meta( 'account-balance', $user->ID ) ); ?>" class="number" /><br />
            <span class="description"><?php _e("Credit balance ie -30"); ?></span>
        </td>
    </tr>
    </table>
<?php }

//save in db
add_action( 'personal_options_update', 'save_extra_user_profile_fields' );
add_action( 'edit_user_profile_update', 'save_extra_user_profile_fields' );

function save_extra_user_profile_fields( $user_id ) {
    if ( !current_user_can( 'edit_user', $user_id ) ) { 
        return false; 
    }
    update_user_meta( $user_id, 'account-balance', $_POST['account-balance'] );
}

如果用户有余额,则在结帐时获取并应用余额

//load at checkout
add_action( 'woocommerce_cart_calculate_fees', 'custom_discount', 10, 1 );

function custom_discount( $user ){
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

        $discount =  esc_attr( get_the_author_meta( 'account-balance', $user->ID ) );

     if (get_the_author_meta( 'account-balance', $user->ID ) ){
        WC()->cart->add_fee('Credit', $discount, true);   
     }
}

似乎在计算运费时,信用费被覆盖/重置,但即使我禁用运费,我也会得到相同的行为。

【问题讨论】:

    标签: wordpress woocommerce cart fee


    【解决方案1】:

    传递给woocommerce_cart_calculate_fees的参数不是$user而是$cart_object

    function custom_discount( $cart_object ) {
        if ( is_admin() && ! defined( 'DOING_AJAX' ) )
            return;
    
        $user_id = get_current_user_id();
    
        $discount = get_user_meta( $user_id, 'account-balance', true );
    
        // True
        if ( $discount ) {
            $cart_object->add_fee( 'Credit', $discount );  
        }
    }
    add_action( 'woocommerce_cart_calculate_fees', 'custom_discount', 10, 1 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 2021-12-17
      • 2019-04-21
      • 2012-12-25
      相关资源
      最近更新 更多