简体   繁体   中英

Get previous post by author in Wordpress

I want to display the previous post written by the current post's author at the bottom of a post.

I know I can use the function get_previous_post() to get the previous post of the current post type, but it's not filterable by author.

I don't want just the most recent post by the author, but the one that came before the post that is being viewed.

This might work. $previous_post will be the last post by the author of the current post.

<?php
$this_post = get_post();

$args = array(
    'author'        =>  $this_post->post_author,
    'post_type'     =>  $this_post->post_type,
    'orderby'       =>  'post_date',
    'order'         =>  'DESC',
    'date_query' => array(
        'before' => $this_post->post_date
    ),
);

$author_posts = get_posts( $args );
$previous_post = $author_posts[0];

I've used date_query which was added in WordPress 3.7: http://codex.wordpress.org/Class_Reference/WP_Query#Date_Parameters

This lets us take the current post's date and use that as our cut-off point. After that it's relatively easy to grab what you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM