Join

Filter Woocommerce Orders by User Role

Don't want to mess with code snippets? Request for this to be a feature of MyListing Pro.

Instructions

  1. Create a new PHP code snippet.
  2. Copy the contents of code snippet below.
  3. Paste the contents into your code snippet.
  4. Review any notes that I’ve provided.
  5. Save and enable the code snippet.
  6. Test.

Snippet

This adds a ‘Select Role’ dropdown to the WooCommerce orders table.

function wpsh_user_role_filter() {

	global $typenow, $wp_query;

	if ( in_array( $typenow, wc_get_order_types( 'order-meta-boxes' ) ) ) {
		$user_role	= '';

		// Get all user roles
		$user_roles = array( 'guest' => 'Guest' );
		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=''><?php _e( 'Select User Role', 'woocommerce' ); ?></option><?php
			foreach ( $user_roles as $key => $value ) :
				?><option <?php selected( $user_role, $key ); ?> value='<?php echo $key; ?>'><?php echo $value; ?></option><?php
			endforeach;
		?></select><?php
	}

}
add_action( 'restrict_manage_posts', 'wpsh_user_role_filter' );

function wpsh_user_role_filter_where( $query ) {

	if ( ! $query->is_main_query() || empty( $_GET['_user_role'] ) || $_GET['post_type'] !== 'shop_order' ) {
		return;
	}

	if ( $_GET['_user_role'] != 'guest' ) {
		$ids = get_users( array( 'role' => sanitize_text_field( $_GET['_user_role'] ), 'fields' => 'ID' ) );
		$ids = array_map( 'absint', $ids );
	} else {
		$ids = array( 0 );
	}

	$query->set( 'meta_query', array(
		array(
			'key' => '_customer_user',
			'compare' => 'IN',
			'value' => $ids,
		)
	) );

	if ( empty( $ids ) ) {
		$query->set( 'posts_per_page', 0 );
	}
}
add_filter( 'pre_get_posts', 'wpsh_user_role_filter_where' );