phparrayswordpresssorting

Wordpress Author Page Custom Order


I have the following code to call only the "authors" from my WordPress for an author page, and need to be able to list them in a custom order.

// Get users
$all_users = get_users('role=author');
$allowed_users = array();
foreach ( $all_users as $user ):
    $wp_user = new WP_User($user->ID);
    if ( !in_array( 'subscriber', $wp_user->roles ) ):
        array_push($allowed_users, $user);
    endif;

endforeach;

// Display users    
foreach ($allowed_users as $user)
{ ?>

... code to display author info.

I need to list the authors in the order of author id: 6,2,5,4,1. This is for a radio station website so I want to list the "authors" in the same order they're on the air.


Solution

  • There's really no custom ordering option that will allow you to define a specific order by ID, but there are ways around it. Something like this should get you started:

    <?php
    $primary_authors = array(6,2,5,4,1);
    $other_authors = new WP_User_Query(array(
        'role'=>'Author',
        'exclude'=>$primary_authors
    ));
    $authors = array();
    foreach($primary_authors as $uid) $authors[] = new WP_User($uid);
    foreach($other_authors->results as $user) $authors[] = $user;
    ?>
    

    What this does is define a very specific order of user IDs you would like to show up first. Then, a second query is made that grabs the rest of the users with a role of Author, excluding the ones defined in $primary_authors.

    We iterate through the $primary_authors array first, and push a new WP_User instance to the $authors array, and then grab the rest of the authors in a second loop if any exist.

    This way, if you create any new Authors they will still be included, but you can pick and choose the ones you would like to be weighted by adding them to the $primary_authors array.