如何获得wordpress中的下一个/上一个帖子href和标题

时间:2012-07-07 23:41:19

标签: php wordpress

这是关于单个帖子的观点。我正试图像这样设置上一个和下一个博客帖子的链接:

<a class="prevpost" href="linktoprevpost" title="prev post's title">&nbsp;</a>
<a class="nextpost" href="linktonextpost" title="next post's title">&nbsp;</a>

其中两个链接都使用display:block和指定的宽度和高度将图像作为背景。链接帖子的标题应该可以通过a-tags的title属性访问,以便用户可以通过悬停看到它们。
我还想限制当前类别的链接帖子。所以我需要找到一种方法来获得

  1. 带有上一个/下一个帖子的href的a-tag
  2. 与当前查看的类别
  3. 属于同一类别
  4. 由于backgroundimage而没有内部文字
  5. 使用title-attribute
  6. 中的上一个/下一个帖子名称
  7. 使用自定义css-class

  8. 类别匹配只需要是第一级,因为我将页面分为3个主要类别。我正在使用

    $a = get_the_category(get_the_ID());
    $cat = $a[0]->name;
    

    获取第一个类别的名称并将其设置为header.php中的附加body-class。也许我可以重复使用它?

    我也发现像这样使用previous_post_link()和next_post_link()

    next_post_link('%link', '', TRUE);
    

    给了我相同类别的帖子没有内容,所以1&amp; 2&amp; 3将被解决。但看来,要获得4&amp;我也需要另外一种方式。

    使用Wordpress版本3.4.1。

3 个答案:

答案 0 :(得分:29)

您无需使用功能和过滤器,只需使用get_adjacent_post代替next_post_linkprev_post_link,请注意get_adjacent_post用于获取上一个和下一个发布,你可以阅读它here 要获取上一篇文章及其标题属性,请使用此

$prev_post = get_adjacent_post(false, '', true);
if(!empty($prev_post)) {
echo '<a href="' . get_permalink($prev_post->ID) . '" title="' . $prev_post->post_title . '">' . $prev_post->post_title . '</a>'; }

要获得下一篇文章及其标题属性,请使用此

$next_post = get_adjacent_post(false, '', false);
if(!empty($next_post)) {
echo '<a href="' . get_permalink($next_post->ID) . '" title="' . $next_post->post_title . '">' . $next_post->post_title . '</a>'; }

答案 1 :(得分:1)

知道了。

现在这是我的代码:

$p = get_adjacent_post(1, '', 1);
if(!empty($p)) echo '<a class="prevpost" href="'.$p->guid.'" title="'.$p->post_title.'">&nbsp</a>';
$n = get_adjacent_post(1, '', 0);
if(!empty($n)) echo '<a class="nextpost" href="'.$n->guid.'" title="'.$n->post_title.'">&nbsp</a>';

该函数返回prev / next帖子的对象,我可以用它来生成我的链接。第一个参数用于限制同一只猫的帖子 昨天我在wordpress codex上搜索了几次,但没有碰到这个功能,现在偶然发现了它
如果某人有更好/更简单/更快的方法,请发布以获得接受的答案。

答案 2 :(得分:-3)

<?
echo '<a href="'.get_permalink( get_the_ID()-1 ).'" title="'.get_the_title( get_the_ID()-1 ).'">Previous</a>'; 
echo '<a href="'.get_permalink( get_the_ID()+1 ).'" title="'.get_the_title( get_the_ID()-1 ).'">Next</a>';

?>