jeudi 26 mai 2016

Wordpress - If else for the latest post in single.php

I created a category where I post a picture everyday. So every single post will have an image and some text.

I created a post navigation using

previous_post_link() and next_post_link()

I add the image via a custom field named featured_img so that I can display the image anywhere I want. So this code lies in single.php to display the image.

$feat_img = get_post_meta($post->ID, 'featured_img', true);
    if ($feat_img) {
        echo "<img src=\" " . $feat_img . " \" > ";
    }

Now, I'd like to have a dynamic link on every image so when the user will click the image he will jump to the next post.

If it is the latest post published the image doesn't have a link. If it's any other post but the last one, the image should have the next_post_link().

So I'm thinking on something like this:

if ( [CODE TO CHECK IF IT IS THE LATEST POST PUBLISHED]) {
    next_post_link('%link', ' <img src=" ' . $feat_img . ' " > ', true);
} else {
    echo "<img src=\" " . $feat_img . " \" > "; 
}

But I can't figure it out how to make this work so that it will add the link using if/else.

So check if the current post is the last one published, and if yes the image won't have a link, but if it is any other post the image should have a href with the link for the next post.

Aucun commentaire:

Enregistrer un commentaire