Search code examples
phpwordpressbuttonwoocommercecheckout

Disable WooCommerce Checkout Place Order Button based on the User ID


With the code below, I am trying to disable the order button for non-allowed users based on their ID, in WooCommerce checkout:

add_filter( 'woocommerce_order_button_html', 'replace_order_button_html', 10, 2 );
function replace_order_button_html( $order_button ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    $wpuser_object = wp_get_current_user_id();
    $allowed_users = array( 1, 2);

    if ( array_intersect($allowed_users, $wpuser_object->id) ){
    
        $order_button_text = __( "Place Order", "woocommerce" );

        $style = ' style="color:#fff;cursor:not-allowed;background-color:#999;"';
        return '<a class="button alt"'.$style.' name="woocommerce_checkout_place_order" id="place_order" >' . esc_html( $order_button_text ) . '</a>';
    }
}

But it doesn't work at all.

What I am doing wrong?


Solution

  • There are some mistakes and unnecessary things in your code:

    • You need to use in_array() instead of array_intersect(),
    • To get the current user ID, use get_current_user_id(),
    • You can add "disabled" selector class instead of custom CSS styling,
    • You need to replace the type attribute value from "submit" to "button", to avoid the order to be placed ("disabled" attribute will not work here),
    • always return the main variable argument at the end when using filter hooks.

    Try the following simplified and revised code:

    add_filter( 'woocommerce_order_button_html', 'disable_conditionally_order_button_html', 10 );
    function disable_conditionally_order_button_html( $button_html ) {
        $allowed_users_ids = array( 1, 2 );
    
        if ( ! in_array( get_current_user_id(), $allowed_users_ids ) ) {
            return str_replace(['type="submit"', 'class="button alt'], ['type="button"', 'class="button alt disabled'], $button_html );
        }
        return $button_html;
    }
    

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

    enter image description here