如果他们的帐户在 WooCommerce 中获得批准,则允许客户通过支票付款

Allow customer to pay by cheque if their account is approved in WooCommerce

默认情况下,商店只接受信用卡,但我需要允许一些预先批准的客户能够通过支票付款。

我使用自定义用户角色和以下代码实现了此功能:

add_filter( 'woocommerce_available_payment_gateways', 'allow_to_pay_by_check' );

function allow_to_pay_by_check( $available_gateways ) {
   if ( isset( $available_gateways['cheque'] ) && ! current_user_can('pay_using_cheque') ) {
      unset( $available_gateways['cheque'] );
   } 
   return $available_gateways;
}

它有效,让他们能够通过支票和信用卡支付。问题是我认为这不应该是用户角色。它应该位于每个客户(用户)帐户详细信息下,作为一个复选框来打开或关闭。这可能吗?

以下将向管理员用户页面添加一个自定义复选框字段,该字段将启用或禁用“支票”付款方式:

// Add allowed custom user field in admin
add_action( 'show_user_profile', 'add_customer_checkbox_field', 10 );
add_action( 'edit_user_profile', 'add_customer_checkbox_field', 10 );
function add_customer_checkbox_field( $user )
{
    ?>
    <h3><?php _e("Payment option"); ?></h3>
    <table class="form-table">
        <tr>
            <th><?php _e("Pay by Cheque"); ?></th>
            <td>
    <?php

    woocommerce_form_field( 'pay_by_cheque', array(
        'type'      => 'checkbox',
        'class'     => array('input-checkbox'),
        'label'     => __('Allowed'),
    ), get_user_meta( $user->id, 'pay_by_cheque', true ) );

    ?>
            </td>
        </tr>
    </table>
    <?php
}

// Save allowed custom user field in admin
add_action( 'personal_options_update', 'save_customer_checkbox_field' );
add_action( 'edit_user_profile_update', 'save_customer_checkbox_field' );
function save_customer_checkbox_field( $user_id )
{
    if ( current_user_can( 'edit_user', $user_id ) ) {
        update_user_meta( $user_id, 'pay_by_cheque', isset($_POST['pay_by_cheque']) ? '1' : '0' );
    }
}

// Enabling or disabling "Cheque" payment method
add_filter( 'woocommerce_available_payment_gateways', 'allow_to_pay_by_cheque' );
function allow_to_pay_by_cheque( $available_gateways ) {
   if ( isset( $available_gateways['cheque'] ) && ! get_user_meta( get_current_user_id(), 'pay_by_cheque', true ) ) {
      unset( $available_gateways['cheque'] );
   }
   return $available_gateways;
}

代码进入您的活动子主题(或活动主题)的 functions.php 文件。已测试并有效。