Home  >  Q&A  >  body text

Hiding specific payment methods is possible for new customers with WooCommerce version 5.6+

<p>I created a script that checks if the user has a completed order. If the user has no completed orders, it disables the payment method "cheque". This function works, but after adding it to my functions.php file, I have severe performance issues when browsing the page. Do you see some optimization possibilities or where the problem might be? </p> <pre class="brush:php;toolbar:false;">function has_bought() { // Get all customer orders $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => get_current_user_id(), 'post_type' => 'shop_order', // WC order article type 'post_status' => 'wc-completed' // Only include orders with status "completed" ) ); // Return "true" when the customer already has an order return count( $customer_orders ) > 0 ? true : false; } add_filter('woocommerce_available_payment_gateways', 'customize_payment_gateways'); function customize_payment_gateways($gateways) { if (!has_bought()) { if (isset($gateways['cheque'])) { // Cancel the "cheque" payment gateway unset($gateways['cheque']); } } return $gateways; }</pre>
P粉283559033P粉283559033450 days ago603

reply all(1)I'll reply

  • P粉985686557

    P粉9856865572023-08-16 09:41:30

    There is no need to use a heavier query to check if a customer has a paying order because there is already a lightweight built-in function in the WC_Customer class using get_is_paying_customer() Method, which uses custom user metadata, is available since WooCommerce version 5.8.

    You can disable "Check" payments for new customers using the following methods:

    add_filter('woocommerce_available_payment_gateways', 'cheque_payment_gateway_only_for_paying_customers');
    function cheque_payment_gateway_only_for_paying_customers($gateways) {
        if ( ! WC()->customer->get_is_paying_customer() && isset($gateways['cheque']) ) {
            unset($gateways['cheque']); // 取消“支票”付款选项
        }
        return $gateways;
    }
    

    Place the code in your child theme’s functions.php file (or in a plugin). Tested and available.

    reply
    0
  • Cancelreply