Untitled
webwizards
plain_text
18 days ago
2.2 kB
4
Indexable
function make_b2bking_custom_field_searchable($query) { global $pagenow, $wpdb; if (!is_admin() || $pagenow !== 'users.php' || empty($_GET['s'])) { return; } $search_term = sanitize_text_field($_GET['s']); // Hook into the actual SQL generation with late priority add_filter('users_pre_query', function($results, $user_query) use ($search_term, $wpdb) { // Skip if this isn't our search query if (empty($_GET['s'])) { return $results; } $search_like = '%' . $wpdb->esc_like($search_term) . '%'; // Add JOIN only if not already added if (strpos($user_query->query_from, 'b2bmeta') === false) { $user_query->query_from .= " LEFT JOIN {$wpdb->usermeta} AS b2bmeta ON {$wpdb->users}.ID = b2bmeta.user_id AND b2bmeta.meta_key = 'b2bking_custom_field_1779'"; } // Add DISTINCT to prevent duplicates if (strpos($user_query->query_fields, 'DISTINCT') === false) { $user_query->query_fields = str_replace( $wpdb->users . '.*', 'DISTINCT ' . $wpdb->users . '.*', $user_query->query_fields ); } // Find the existing search conditions and ADD to them (not replace) $custom_search = $wpdb->prepare("b2bmeta.meta_value LIKE %s", $search_like); // Look for existing search patterns and modify them if (preg_match('/\(([^()]*(?:user_login|user_email|display_name)[^()]*)\)/i', $user_query->query_where, $matches)) { // Found existing search conditions, add ours to them $new_conditions = "({$matches[1]} OR {$custom_search})"; $user_query->query_where = str_replace($matches[0], $new_conditions, $user_query->query_where); } else { // No search conditions found, add ours to the WHERE clause $user_query->query_where .= " AND ({$custom_search})"; } return $results; }, 20, 2); // Higher priority (20) to run after other plugins } add_action('pre_get_users', 'make_b2bking_custom_field_searchable', 1);
Editor is loading...
Leave a Comment