Limit get_next_post to posts from the same author

Question

I’m trying to limit get_next_post and get_previous_post to the same author with a filter. I’m using it in a loop, as I need to display the previous and next post for each post I’m looping through.

This is what I have tried so far in my functions.php file:

// PREVIOUS AND NEXT POST FROM SAME AUTHOR
add_filter( "get_next_post_where", function($where, $in_same_term, $excluded_terms, $taxonomy, $post){
  $where .= " AND p.post_author='".$post->post_author."'";
  return $where;
}, 10, 5);

add_filter( "get_previous_post_where", function($where, $in_same_term, $excluded_terms, $taxonomy, $post){
  $where .= " AND p.post_author='".$post->post_author."'";
  return $where;
}, 10, 5);

In the actual template, I use this loop:

$story_loop = new WP_Query( array(
    'post_type' => 'stories',
    'posts_per_page' => -1
  )
);

while ( $story_loop->have_posts() ) : $story_loop->the_post();

  $next_post = get_next_post();
  $prev_post = get_previous_post();

endwhile; wp_reset_query();

However, $next_post and $prev_post are not limited to the same author.

I’d prefer to avoid making a new loop just to get the next post by the same author for each post, so filtering get_next_post would be ideal.

0
lastnoob 3 months 0 Answers 15 views 0

Leave an answer