一般我们添加上一篇和下一篇文章时的代码是这样子的:
1 2 3
| <?php previous_post_link('%link','%title',true) ?> <?php next_post_link('%link','%title',true) ?>
|
该代码最终解析出来的代码大概如下:
1 2 3
| <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。通过这两个函数我们可以获取到上一篇和下一篇文章的相关信息。
大家可以到官网看看这两个函数的介绍。
1 2
| <?php $prev_post = get_previous_post();$next_post = get_next_post();?>
|
上一篇文字:
1 2
| <?php echo $prev_post->post_title; ?>
|
上一篇链接:
1 2
| <?php echo get_permalink( $prev_post->ID ); ?>
|
下一篇文字:
1 2
| <?php echo $next_post->post_title; ?>
|
下一篇链接:
1 2
| <?php echo get_permalink( $next_post->ID ); ?>
|
具体干货代码,解决方法,只要将:
1 2 3
| <?php previous_post_link('%link','<<') ?> <?php next_post_link('%link','>>') ?>
|
替换成:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?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”。
总结