Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Add the ability to filter WooCommerce orders by role in wp-admin
<?php
/**
* 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 } ?>
</select>
<?php
endif;
}
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'])) {
return;
}
// 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(
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');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment