I have used get_previous_post to get the previous post of my custom post type. When I try that by doing

 $prevPost = get_previous_post();

I get a post object containing my previous post. So I then tried to set it up so that I could get the post data

 $prevPost = get_previous_post(true);
    if($prevPost) {
        $args = array(
            'posts_per_page' => 1,
            'include' => $prevPost->ID
        $prevPost = get_posts($args);
        foreach ($prevPost as $post) {
           ?> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>

I want to be able to get the featured image and the permalink of the next post which doesn't appear to be available without setting up the post data. My problem is that when I do this, I get an empty array.

Why is that? It's there without setting up post data and disappears when I do set it up.

  • 1
    have you tried adding the 'post_type' to the posts query? or to work directly with the post object via 'get_permalink()' and 'get_the_post_thumbnail()'? – Michael Sep 25 '17 at 3:11
  • Michael, your suggestion worked. Add your comment as an answer and I will accept it. – Jamie Sep 25 '17 at 3:16

Depending on context, you may need global $post; first, so you're not operating on a different local var. You also already have a post object, so you could just assign that directly to $post before calling setup_postdata...

However, you can skip all that and use functions that accept a post object argument-

$prevPost = get_previous_post(true);
if($prevPost) {
    echo get_permalink($prevPost);
    echo get_the_post_thumbnail($prevPost, 'thumbnail');

Most of the template functions have alternates that work this way.

| improve this answer | |
  • Milo, Thank you for the suggestion. That is a good idea. I added the post type as Michael suggested above and it worked. However, I found your suggestion to be useful as I did not think about doing it that way. I will need to remember this kind of way for future projects as I do believe it will come in handy. – Jamie Sep 25 '17 at 3:18
  • It may have worked, but it's completely redundant- you have the previous post object already, you don't need to query for it again. – Milo Sep 25 '17 at 12:19
  • Good point. I have changed it to your method – Jamie Sep 26 '17 at 1:35

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.