wordpress: previous_post_link() / next_post_link()

2019-05-07 12:10发布

I am having trouble with the previous_post_link() and next_post_link() functionality. When there is no previous post, the function previous_post_link() does not display a link, likewise for the next_post_link() and the last post. I would like to have a placeholder image so that the design stays consistent.

Currently I have images of green arrows pointing left and right, I would like to place an image of a grey arrow if there are no more posts to go back to.

Is there a way to use the next_post_link()/previous_post_link() functions but not have the link removed.

I also wonder if there is a way for the links to cycle, so that if you come to the most recent post, the next post link would bring you back to the first post.

************ UPDATED ************

Here is the code, based on "silent's" advice (accepted answer) to use get_adjacent_post():

<?php 
    if(get_adjacent_post(false, '', true)) { 
        previous_post_link('%link','<img src="larr.gif"/>'); 
    }
    else { 
        echo '<img src="larr2.gif"/>'; 
    }; 

    if(get_adjacent_post(false, '', false)) { 
        next_post_link('%link','<img src="rarr.gif"/>'); 
    }
    else { 
        echo '<img src="rarr2.gif">'; 
    }; 
?>

标签: wordpress
3条回答
看我几分像从前
2楼-- · 2019-05-07 12:50

So you can "capture" what next_post_link() and previous_post_link() return using ob_start() and ob_get_clean(), then apply a conditional to it.

Code in practice:

$previous_string = "&lt;-Back";
ob_start(); // start output buffering
previous_post_link("%link", $previous_string);
$previous_link = ob_get_clean(); // stop output buffering and store

if ($previous_link == '') {
  echo '<span style="color: #ccc">' . $previous_string . '</span>';
} else {
  echo $previous_link;
}
查看更多
一纸荒年 Trace。
3楼-- · 2019-05-07 13:05

Why cant you try the below?

<div style="float:right"><?php if(get_previous_posts_link()) { previous_posts_link('Newer Entries &raquo;'); } else { echo 'No Newer Entries'; } ; ?></div>

Alternatively to display Next and Previous Post Links to Blog post you can easily do that. This is very well explained at globinch.com (WordPress Tips : How to Add Next and Previous Post Links to Blog? )

http://www.globinch.com/2010/10/12/wordpress-tips-how-to-add-next-and-previous-post-links-to-blog/

查看更多
淡お忘
4楼-- · 2019-05-07 13:15

I never try this myself. However, you may refer to this post. It uses get_adjacent_post().

查看更多
登录 后发表回答