How can i get the last post from wp multisite?

I have to get the last post from my Multisite network on WordPress. For now I use this code for display the last updated post after a cycle on each blog_id:

<?php

$blogs = get_last_updated(' ', 0, 1);
foreach ($blogs AS $blog);
    switch_to_blog($blog["blog_id"]);
        $lastposts = get_posts('numberposts=1&orderby=date');
        foreach($lastposts as $post) : setup_postdata($post);?>

But if I want to get the last post — not the last post updated — how can I do that? Because if I change and refresh a post I get the post like the last on main page. But this is not the real last post.

Update – This is the full version, i have also used the restore_current_blog():

<?php

    $blogs = get_last_updated(' ', 0, 1);
    foreach ($blogs AS $blog);
        switch_to_blog($blog["blog_id"]);
            $lastposts = get_posts('numberposts=1&orderby=date');
            foreach($lastposts as $post) : setup_postdata($post);?> 
    <div class="container-img">
     <a class="anteprima_princ" href="https://wordpress.stackexchange.com/questions/133433/<?php echo get_page_link($post->ID); ?>" title="Permanent Link to <?php the_title(); ?>"><?php the_post_thumbnail('immagine-principale'); ?></a>
     </div>
                <h2 class="entrytitlepost"><a href="https://wordpress.stackexchange.com/questions/133433/<?php echo get_page_link($post->ID); ?>" title="<?php echo $post->post_title; ?>"><?php the_title(); ?></a></h2>

                  <div class="post-content-princ">
        <p><?php the_content_rss('...', FALSE, '', 40); ?></p>
        <div id="lt">
        <div id="leggitutto"><div id="croce"><div id="alto"></div><div id="largo"></div></div><a class="lt" href="https://wordpress.stackexchange.com/questions/133433/<?php echo get_page_link($post->ID); ?>" title="<?php echo $post->post_title; ?>">LEGGI TUTTO</a></div>
      </div>
      </div>

         <?php endforeach ; ?>

                        <?php restore_current_blog(); //switched back to main site ?>

2 Answers
2

The orderby-parameter should be post_date instead of date.

your code would look something like this:

$blogs = get_last_updated(' ', 0, 1);
foreach ($blogs AS $blog) {
    switch_to_blog($blog["blog_id"]);
    $args = array(
        'orderby'         => 'post_date',
        'order'           => 'DESC',
        'numberposts'     => 1,
        'post_type'       => 'post',
        'post_status'     => 'publish',
        'suppress_filters' => true
    );
    $lastposts = get_posts( $args );

    foreach($lastposts as $thispost) {

        setup_postdata($thispost);

    }
    restore_current_blog();
}

Please do not forget to call restore_current_blog() in your foreach. If you used switch_to_blog() more than once before calling restore_current_blog(), it won’t work anymore.

Leave a Comment