get_previous_post not working as expected

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();
 var_dump($prevPost);

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) {
            setup_postdata($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.

Topic previous posts Wordpress

Category Web


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.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.