0

I want to list all sites in the multi site network in alphabetical order? Right now, the code lists by registered date

<?php
// Query for getting blogs
            $blogs = $wpdb->get_results( $wpdb->prepare("SELECT blog_id, domain, path FROM $wpdb->blogs WHERE site_id = %d AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0' ORDER BY registered DESC", $wpdb->siteid), ARRAY_A );

            // put it in array  
            foreach ( (array) $blogs as $details ) {$blog_list[ $details['blog_id'] ] = $details;}
            unset( $blogs );
            $blogs = $blog_list;

            // if is valid array
            if (is_array( $blogs ) ){
                    echo '<ul>';
                    $array= array();
                    // reorder
                    $array= array_slice( $blogs, 0, count( $blogs ) );
                    for($i=0;$i<count($array);$i++){
                    // get data for each id
                    $blog = get_blog_details( $array[$i]['blog_id'] );
                    // print it
                    echo '<li><a href="'.$blog->siteurl.'">'.$blog->blogname.'</a></li>';
                    }
                    echo '</ul>';
            }
            ?>
1

You can try to replace:

ORDER BY registered DESC

with:

ORDER BY domain ASC, path ASC

to get the sites in an alphabetical order.

1

If you want to sort the sites by their site name, and not by their path, use strcasecmp() in a callback for uasort().

Example

is_admin() || add_action( 'shutdown', function() {

    $sites = wp_get_sites();

    foreach ( $sites as $i => $site ) {

        switch_to_blog( $site[ 'blog_id' ] );
        $sites[ $i ][ 'name' ] = get_bloginfo();
        restore_current_blog();
    }

    uasort( $sites, function( $site_a, $site_b ) {
        return strcasecmp( $site_a[ 'name' ], $site_b[ 'name' ] );
    });

    print '<pre>' . print_r( $sites, 1 ) . '</pre>';
});
  • Good idea (+1). I wonder if we need restore_current_blog() inside the foreach loop? Isn't it enough to have it after the loop? – birgire May 22 '14 at 10:25
  • 1
    @birgire Not necessary. – fuxia May 22 '14 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.