1

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

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

添加用户自定义字段

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);   
     }
}

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

4

1 回答 1

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 );
于 2020-05-01T10:39:06.913 回答