Skip to content

Instantly share code, notes, and snippets.

Last active March 22, 2023 21:45
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save doubleedesign/50afece9c9d709a078445e84a5eae05a to your computer and use it in GitHub Desktop.
Add the ability to filter WooCommerce orders by role in wp-admin
* Add role drop-down to orders screen
function doublee_add_order_user_role_filter_selectbox() {
global $typenow, $wp_query;
if (in_array($typenow, wc_get_order_types('order-meta-boxes'))) :
$user_role = '';
// Get all user roles
$user_roles = array();
foreach(get_editable_roles() as $key => $values) {
$user_roles[$key] = $values['name'];
// Set a selected user role
if (!empty($_GET['_user_role'])) {
$user_role = sanitize_text_field($_GET['_user_role']);
// Display drop down
?><select name='_user_role'>
<option value='all'><?php _e( 'All user roles', 'woocommerce' ); ?></option><?php
foreach($user_roles as $key => $value) { ?>
<option <?php selected($user_role, $key); ?> value='<?php echo $key; ?>'><?php echo $value; ?></option>
<?php } ?>
add_action('restrict_manage_posts', 'doublee_add_order_user_role_filter_selectbox');
* Filter orders by user role using the custom selectbox's value
* @param $query
function doublee_filter_order_list_by_role($query) {
// Exit if no user role was submitted with the filters
if(!$query->is_main_query() || !isset( $_GET['_user_role'])) {
// Get all users with the submitted role
$ids = get_users(array('role' => sanitize_text_field($_GET['_user_role']), 'fields' => 'ID'));
$ids = array_map('absint', $ids);
// If retail, add guests
if(sanitize_text_field($_GET['_user_role']) == 'customer') {
$ids[] = 0;
// Update the query
$query->set('meta_query', array(
'key' => '_customer_user',
'compare' => 'IN',
'value' => $ids,
// No users with that role, return nothing
if(empty($ids)) {
$query->set( 'posts_per_page', 0 );
add_filter('pre_get_posts', 'doublee_filter_order_list_by_role');
Copy link

Hi @yaeru, this can go in your theme's functions.php (or a file loaded from there if you are separating things out).

If you're developing a plugin for your site's customisations, even better - it can go in there instead (exactly where depends how your plugin is structured).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment