Search code examples
phpwordpresswoocommerce

Disable access to WooCommerce Admin Payments page for specific users


I have this code to disable/remove the payments tab from the WooCommerce settings tab, however, the users can still directly access the payments settings / payment methods using the direct url like wp-admin/admin.php?page=wc-settings&tab=checkout

add_filter( 'woocommerce_settings_tabs_array', 'wd_remove_woocommerce_payment_tab', 200, 1 );
function wd_remove_woocommerce_payment_tab( $tabs_array ) {
    
    $wd_allowed_users = array("asd", "asd", "asd");
    $wd_user = wp_get_current_user();
    if ( in_array(strtolower($wd_user->user_login), $wd_allowed_users)){
        unset( $tabs_array['checkout'] );
    }
    return $tabs_array;
}

Solution

  • You can try the following, that will redirect the non-allowed users to WooCommerce Admin General settings, when trying to access WooCommerce Admin Payments page:

    add_action( 'woocommerce_init', 'role_based_redirect' );
    function role_based_redirect() {
        global $pagenow, $current_user;
    
        // Define allowed users below
        $non_allowed_users = array("abc", "afi", "asd");
    
        // Targetting WooCommerce Admin Payments page
        if ( is_admin() && $pagenow === 'admin.php' && isset($_GET['page'],$_GET['tab']) 
        && $_GET['page'] === 'wc-settings' && $_GET['tab'] === 'checkout' 
        && in_array( strtolower($current_user->user_login), $non_allowed_users ) )
        {
            wp_redirect( admin_url( 'admin.php?page=wc-settings' ) );
            exit();
        }
    }
    

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