almostsultry
almostsultry

Reputation: 13

WooCommerce auto set orders to "completed" status for a specific user role

Based on Change COD default order status to "On Hold" instead of "Processing" in Woocommerce answer code, where I have changed the default status to "completed", how could set, by default, orders with Cash on delivery payment method (COD) to "completed" status for a specific user role?

What is missing from the code, is the specific user role. How to target a specific user role?

This would allow me to use the default WooCommerce cart experience to handle cash transactions at farmer's markets without needing to go back and remember specific transactions from a hectic and overheated day. This also means no reconciliation is necessary other than totaling the cash drawer and filtering the order records because the WooCommerce store is the single source of truth.

Upvotes: 1

Views: 360

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 254363

You can target a specific user role by using WC_Order get_user() method and you will be able to get the user roles as follow:

$user = $order->get_user(); // Get user

$user_roles = $user->roles; // Get user roles

See: How to get Customer details from Order in WooCommerce?

Then now you will set orders with COD payment to "completed status", for a specific user role:

add_filter( 'woocommerce_cod_process_payment_order_status', 'change_cod_payment_order_status', 10, 2 );
function change_cod_payment_order_status( $order_status, $order ) {
    // Get user
    $user = $order->get_user();

    $targeted_user_role = 'administrator'; // Here define user role

    if ( in_array( $targeted_user_role, $user->roles ) )
        return 'completed';

    return $order_status;
}

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


Then in checkout, if you want you allow COD payments, only for a specific user role, use also:

add_filter( 'woocommerce_available_payment_gateways', 'custom_available_payment_gateways' );
function custom_available_payment_gateways( $available_gateways ) {
    // Not in backend (admin)
    if( is_admin() ) 
        return $available_gateways;

    $targeted_user_role = 'administrator'; // Here define user role

    if ( ! current_user_can( $targeted_user_role && isset( $available_gateways['cod'] ) )
        unset( $available_gateways['cod'] );
    }

    return $available_gateways;
} 

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

Upvotes: 1

Related Questions