Developers

Adding Fields to the User Search

Published

The Visible to specific users field on a coupon’s Usage restriction tab searches your customers as you type. Out of the box it matches username, email address, nicename, display name, first name and last name. If your customers are better known by another field, such as a membership number, a company name or a Discord username, two filters add it to the search and to each result’s label.

What the search matches

Typing two or more characters runs two WordPress user queries and merges the results, up to 20 customers:

  • WordPress’s own columns: user_login, user_email, user_nicename and display_name, matched anywhere in the value.
  • User meta: each key in the ssc_user_search_meta_keys list, matched with LIKE. The default list is first_name and last_name.

Each result reads Name - email (username). Every extra key you add is appended as [Label: value] when the customer has a value for it.

Add a field: ssc_user_search_meta_keys

The filter receives an array of user meta key => label. Add your key and return the array:

add_filter( 'ssc_user_search_meta_keys', function ( $keys ) {
	$keys['membership_number'] = 'Member';
	return $keys;
} );

A customer with membership_number set to M-1042 is found by typing 1042, and shows as Jane Smith - jane@example.com (jsmith) [Member: M-1042].

Keys are passed through sanitize_key(), so use the meta key exactly as it is stored, in lower case. Values must be plain strings to appear in the label; arrays and objects are searched by WordPress but not shown.

Performance Tip

Each extra key adds an OR to the user meta query. WordPress indexes meta_key but not meta_value, and a LIKE '%term%' match cannot use an index, so on a store with hundreds of thousands of customers keep the list short.

Change the placeholder: ssc_user_search_placeholder

The placeholder reads “Search by name, email or username…”. Tell your team about the new field by changing it:

add_filter( 'ssc_user_search_placeholder', function () {
	return 'Search by name, email, username or member number…';
} );

Where to put the code

Put both filters in a small plugin of your own or in your child theme’s functions.php, not in Super Speedy Coupons itself, so updates don’t remove them.

Who can search

The search is an admin-ajax request checked with a nonce and the manage_woocommerce capability, so only shop managers and administrators can run it.

Further reading

what a chosen customer sees

Written for Super Speedy Coupons 1.5.4.

Comments