Last active
February 2, 2016 18:23
-
-
Save tobiasschutter/28d938b14a730e8cd0b3 to your computer and use it in GitHub Desktop.
Add custom fields for users to the search in the wp-admin
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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