最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to query most recent post for each author?

programmeradmin1浏览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!

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!

Share Improve this question asked Feb 7, 2019 at 4:44 HBCondoHBCondo 1537 bronze badges 1
  • Thanks for the answers thus far. Are there any solutions that do not involve joins or loops to help scale more? – HBCondo Commented Feb 7, 2019 at 8:02
Add a comment  | 

2 Answers 2

Reset to default 2

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 );

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();

}
发布评论

评论列表(0)

  1. 暂无评论