0

Can anyone provide a sample MySQL or WP_Query code snippet that returns the most recent post for each author on a single WordPress site? For example, if the site has 10 authors but 500 posts, then the query would return 10 records where each record is the most recent post by each author. Thanks!

  • Thanks for the answers thus far. Are there any solutions that do not involve joins or loops to help scale more? – HBCondo Feb 7 at 8:02
0

You can write a SQL query to achieve this:

<?php

$sql = <<<SQL
SELECT
    p.ID,
    p.post_title,
    p.post_author
FROM {$GLOBALS['wpdb']->posts} p INNER JOIN (
    SELECT ID, post_title
        FROM {$GLOBALS['wpdb']->posts} ORDER BY post_date DESC
    ) s ON p.ID=s.ID
WHERE
    p.post_type = 'post'
AND
    p.post_status = 'publish'
GROUP BY
  p.post_author
SQL;

$rows = $GLOBALS['wpdb']->get_results( $sql );
-1

You could first get the users and then run a WP_Query for each:. (That would be the fast, easy, but non-optimized way to do it)

$users = get_users( );
foreach ( $users as $user ) {

    $args = array(
        'post_type'              => array( 'post' ),
        'author'                 => $user->ID
        'posts_per_page'         => '1',
        'order'                  => 'DESC',
        'orderby'                => 'date',
    );
    $query = new WP_Query( $args );
    if ( $query->have_posts() ) {
        while ( $query->have_posts() ) {
            $query->the_post();
            // do something
        }
    }
    wp_reset_postdata();

}
  • 1
    Bear in mind that this could very expensive if your site has a lot of users, as each user essentially generates a hit to the database for the post. – phatskat Feb 7 at 5:38

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.