Hide specific payment methods for new customers in WooCommerce 8+
P粉199248808
P粉199248808 2023-08-15 21:47:22
0
1
550
<p>I created a script to check if the user has a completed order. If the user has no completed order, it disables the payment method "cheque". This script 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', // Post type of WC order 'post_status' => 'wc-completed' // Only 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><br /></p>
P粉199248808
P粉199248808

reply all(1)
P粉156415696

No need to repeat the query to check if the customer has a paid order, there is already a lightweight built-in function in the WC_Customer class, use get_is_paying_customer()Method, which uses a metadata specific to the user.

You can use it like this to disable the "Check" payment method 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']); // 取消“支票”付款选项
    }
    return $gateways;
}

Put the code into your child theme’s functions.php file (or into a plugin). Tested and working fine.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!