【问题标题】:Allow customer to pay by cheque if their account is approved in WooCommerce允许客户通过检查他们的帐户是否在 WooCommerce 中获得批准来付款
【发布时间】:2020-12-05 00:47:36
【问题描述】:

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

我使用自定义用户角色和以下代码来完成这项工作:

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

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

【问题讨论】:

    标签: php wordpress checkbox woocommerce payment-method


    【解决方案1】:

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

    // 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 文件中。经过测试并且可以工作。

    【讨论】:

    • 谢谢!这可行,但有一个小问题与我之前的代码相同。支票付款现在应该是默认选择,但它不是。即使我在付款方式下进行了支票付款#1,也选择了信用卡。当用户启用此功能时,是否默认选择支票付款?
    • @user1822824 这就是你问的:“问题是我不认为这应该是一个用户角色。它应该位于每个客户(用户)帐户详细信息下复选框来打开或关闭。这可能吗?"。所以我的答案代码回答了您最初的问题:它在管理用户页面中添加了一个复选框选项以允许通过支票付款(默认情​​况下不允许)......您在最初的问题中没有询问有关默认付款选择的任何内容。请注意,关于 StackOverFlow 的规则当时是一个问题。
    猜你喜欢
    • 2011-05-15
    • 1970-01-01
    • 1970-01-01
    • 2018-09-23
    • 2013-08-15
    • 1970-01-01
    • 2012-08-26
    • 2013-05-26
    • 2013-09-03
    相关资源
    最近更新 更多