Ordering users of a specific role by last name

I’m trying to display a list of authors by their last name. I can get the list to display but as yet I don’t seem to be able to order the list by last name. Any help would be greatly appreciated. Josh

<?php
    $args  = array(
    // search only for Authors role
    // order results by display_name
    'orderby' => 'meta_value',
    'meta_key ' => 'last_name',
    'role' => 'guest-teacher'



    // check for two meta_values
    );
    // Create the WP_User_Query object
    $wp_user_query = new WP_User_Query($args);
    // Get the results
    $authors = $wp_user_query->get_results();
    // Check for results
    if (!empty($authors))
    {
        echo '<ul class="permanent">';
        // loop trough each author
        foreach ($authors as $author)
        {
            // get all the user's data
            $author_info = get_userdata($author->ID);
            $url = get_author_posts_url($author->ID);  

    ?>


        <h3><a href="<?php echo $url; ?>" rel="nofollow noreferrer noopener"><?php echo $author_info->last_name; ?>         </a></h3>

            <?php
        }
        echo '</ul>';
    } else {

    }
    ?>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

There is apparently an open ticket about this bug.

Here is a workaround that I tested:

$args  = array(
    'meta_key' => 'last_name',
    'role'     => 'guest-teacher'
);

$wp_user_query = new WP_User_Query($args);
$wp_user_query->query_orderby = str_replace( 'user_login', 'wp_usermeta.meta_value', $wp_user_query->query_orderby );
$wp_user_query->query();

$authors = $wp_user_query->get_results();

Problem with this is that it runs the query twice.

Method 2

The following works on my install:

$args  = array(
        'orderby'   => 'meta_value',
        'order'     => 'DESC',
        'meta_key'  => 'last_name',
        'role'      => 'subscriber'
    );

So did you try:

$args  = array(
        'orderby'   => 'meta_value',
        'order'     => 'DESC',
        'meta_key'  => 'last_name',
        'role'      => 'guest-teacher'
    );

and change the order parameter to DESC or ASC to check if it has any effect?

ps: And do you have the lastname filled out for these users?


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x