Skip to content

Instantly share code, notes, and snippets.

@tobiasschutter
Last active February 2, 2016 18:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tobiasschutter/28d938b14a730e8cd0b3 to your computer and use it in GitHub Desktop.
Save tobiasschutter/28d938b14a730e8cd0b3 to your computer and use it in GitHub Desktop.
Add custom fields for users to the search in the wp-admin
<?php
/**
* Add custom fields for users to the search in the wp-admin
*/
function codepress_search_user_custom_fields( $user_query ) {
// Fill in the custom fields you want to add to the search
$custom_fields = array(
'my_custom_field_1',
'my_custom_field_2'
);
if ( ! is_admin() || empty( $_GET['s'] ) || ! empty( $user_query->query_vars['custom_field_search'] ) ) {
return $user_query;
}
global $wpdb;
$user_ids = $wpdb->get_col(
$wpdb->prepare( "
SELECT DISTINCT u1.user_id
FROM {$wpdb->usermeta} u1
INNER JOIN {$wpdb->usermeta} u2 ON u1.user_id = u2.user_id
WHERE ( u1.meta_key IN ('" . implode( "','", $custom_fields ) . "') AND u1.meta_value LIKE '%%%s%%' )
",
esc_attr( $_GET['s'] )
)
);
if ( $user_ids ) {
$user_query->query_where .= " OR {$wpdb->users}.ID IN (" . implode( ',', $user_ids ) . ")";
}
$user_query->query_vars['custom_field_search'] = true;
}
add_action( 'pre_user_query', 'codepress_search_user_custom_fields' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment