一般我们添加上一篇和下一篇文章时的代码是这样子的:
<?php previous_post_link('%link','%title',true) ?>
<?php next_post_link('%link','%title',true) ?>
该代码最终解析出来的代码大概如下:
<a href="……" rel="external nofollow" rel="external nofollow" > …… </a> <a href="……" rel="external nofollow" rel="external nofollow" > …… </a>
这样子的结构是非常简单,如果我要增加 title、target 等属性值时,单靠上面两个函数是办不到的。
其实要解决这个问题很简单,不知道大家有没有接触到这两个函数:get_previous_post、get_next_post。通过这两个函数我们可以获取到上一篇和下一篇文章的相关信息。
大家可以到官网看看这两个函数的介绍。
<?php $prev_post = get_previous_post();$next_post = get_next_post();?>
上一篇文字:
<?php echo $prev_post->post_title; ?>
上一篇链接:
<?php echo get_permalink( $prev_post->ID ); ?>
下一篇文字:
<?php echo $next_post->post_title; ?>
下一篇链接:
<?php echo get_permalink( $next_post->ID ); ?>
好了,下面就来干货,说下解决问题的方法。只要将:
<?php previous_post_link('%link','<<') ?>
<?php next_post_link('%link','>>') ?>
替换成:
<?php $prev_post = get_previous_post(); if (!empty( $prev_post )): ?> <a title="<?php echo $prev_post->post_title; ?>" href="<?php echo get_permalink( $prev_post->ID ); ?>" rel="external nofollow" ><?php echo $prev_post->post_title; ?></a> <?php endif; ?> <?php $next_post = get_next_post(); if (!empty( $next_post )): ?> <a title="<?php echo $next_post->post_title; ?>" href="<?php echo get_permalink( $next_post->ID ); ?>" rel="external nofollow" ><?php echo $next_post->post_title; ?></a> <?php endif; ?>
通过上面的替换,问题就完美解决了。除了可以添加 title 属性外,大家如果有需要也可以加上新窗口打开的属性:target:”_blank”。
版权声明:如发现本站有涉嫌抄袭侵权/违法违规的内容请联系客服!




