Dave McCourt thinks some thoughts...

WP User filtering

Posted in: Code snippets, WordPress

I needed to add a drop down filter on the WP Admin Users page so that users could be filtered by a custom field (in this case the user’s region)


<?php
// Adds a dropdown to filter users based on a meta field
function banana__user_table_filtering() {

    global $pagenow;

    if (is_admin() && $pagenow == 'users.php') {
 
    echo '';
     $field_key = "field_53480bf062cd5"; $field = get_field_object($field_key);
     if ($field) {
         echo '<select name="region" style="float: none; margin-left: 8px; margin-right: 3px;">
         <option value="">Filter by region...</option>';
         foreach($field['choices'] as $k => $v) {
             if ($k == $_GET['region']) {
                 echo '<option value="' . $k . '" selected="selected">' . $v . '</option>';
             } else {
                 echo '<option value="' . $k . '">' . $v . '</option>';
             }
         }
         echo '</select>
         <input id="post-query-submit" class="button" type="submit" value="Filter" name="">';
     }
     echo '';
 
    }

}

add_action('restrict_manage_users', 'banana__user_table_filtering');

// Updates user query based on filtering criteria
function banana__user_table_filter($query) {
 
    global $pagenow;

    if (is_admin() && $pagenow == 'users.php' && isset($_GET['region'])) {
        $region = wp_strip_all_tags($_GET['region']);
        $meta_query = array(
            array(
           'key' => 'region',
           'value' => $region
           )
     ); 
 
     $query->set('meta_key', 'region');
     $query->set('meta_query', $meta_query);

    }
 
}

add_filter('pre_get_users','banana__user_table_filter');
?>