2

I created a script checking if the user has a a completed order. If the user has no completed order it is disabling the payment method "cheque". This works but after adding it my functions.php i get serious performance problems on my page while navigating thorugh it. Do you see some possiblilites to optimize it or where the problem could be?

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 orders post type
        'post_status' => 'wc-completed' // Only orders with status "completed"
    ) );
    // return "true" when customer has already one 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'])) {
            // Unset the 'cheque' payment gateway
            unset($gateways['cheque']);
        }
    }
    return $gateways;
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
public9nf
  • 1,311
  • 3
  • 18
  • 48

1 Answers1

1

Instead of using a heavier query to check that a customer has a paid order, there is already a lightweight built-in feature in WC_Customer Class with get_is_paying_customer() method, that uses dedicated user metadata, available since WooCommerce version 5.8+.

You can use it this way, to disable "cheque" payments for new customers:

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']); // Unset 'cheque' payment option
    }
    return $gateways;
}

Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399