wordpress的文章页页有实现上一篇下一篇的功能函数,不过我们想在单页page.php里面实现上一页下一页的功能,previous_post_link()和next_post_link() 函数还不能完全满足我的需要,所以就自己写函数实现。
页面有分级功能,需求是按 menu order 排序的子级页面之间有上一篇、下一篇链接,如:
themes(父级页面)
---- zbench(子级页面1)
---- zborder(子级页面2)
---- zsofa(子级页面3)
如果当前页面是 zborder,那么就要上一篇链接是 zbench 的,下一篇链接是 zsofa 的。
把下面函数代码放入 functions.php(注:函数随手写的,可能不够精简)/*** get subpage previous/next page link by zwwooooo*/function subpage_nav_link($prevtext='', $nexttext='') {global $post;if ( !$post->post_parent ) return null; //如果不是子页面返回null$args = array('sort_order' => 'asc','sort_column' => 'menu_order','child_of' => $post->post_parent,'post_type' => 'page');$pages = get_pages($args);$num = count($pages);$i = 0;$index = -1;foreach ($pages as $page) {if ($page->id == $post->id) {$index = $i;break;}++$i;}if ($i == 0) {$prev = '';$next = $pages[$index+1];} elseif ($i == $num-1) {$prev = $pages[$index-1];$next = '';} else {$prev = $pages[$index-1];$next = $pages[$index+1];}if ($prev) {if ($prevtext) {if ( substr_count($prevtext, '%title') > 0 ) {$explode = explode('%title', $prevtext);$prevtext = $explode[0] . get_the_title($prev->id) . $explode[1];}} else {$prevtext = get_the_title($prev->id);}$prevlink = 'id). '>' . $prevtext . '';}if ($next) {if ($nexttext) {if ( substr_count($nexttext, '%title') > 0 ) {$explode = explode('%title', $nexttext);$nexttext = $explode[0] . get_the_title($next->id) . $explode[1];}} else {$nexttext = get_the_title($next->id);}$nextlink = 'id). '>' . $nexttext . '';}return array($prevlink, $nextlink);}
[函数]
subpage_nav_link($prevtext, $nexttext)
[参数]
$prevtext: 为前一篇文章链接文字,为空时默认是页面标题
$nexttext: 为下一篇文章链接文字,为空时默认是页面标题;
例如:一般的主题是在 page.php 的 loop 循环里面(不知道就在 the_content(); 下面吧)插入调用代码
复制代码 代码如下:
if ( function_exists('subpage_nav_link') ) {
if ( $subpage_nav_link = subpage_nav_link() ) {
echo $subpage_nav_link[0]; //上一篇(页面)链接
echo $subpage_nav_link[1]; //下一篇(页面)链接
}
}
?>
注:可以用 if (!$subpage_nav_link[0]) 来判断有没有上一篇,同样 if (!$subpage_nav_link[1]) 来判断有没有下一篇。
ps: $prevtext 和 $nexttext 还支持字符组合,如 subpage_nav_link('oo %title xx', '') 这样的话,前一篇文章链接文章会变成“oo 页面名 xx”
另一篇实用文章:实现wordpress文章页调用同分类上/下一篇文章
wordpress提供的显示上一篇、下一篇文章的函数代码是按照发布顺序调用的,前几天做的wordpress小说模板,由于使用每个分类添加一部小说《博客吧首款wordpress小说网站主题模板wpnovel》,如果使用这样的上下篇文章调用顺序显示不合适,让文章页显示同分类下的上一篇、下一篇文章才是正道,wordpress是强大的,总能满足用户的想法,通过搜索找到了相关的函数代码。
默认直接调用的代码
当文章处于首篇或末篇时,会显示空白,但可以通过增加判断还填补空白
经过测试虽然显示同分类下的文章,但首篇文章和末尾的文章会不显示对应的提示信息“已是最后文章”和“已是最后文章”。只要在get_previous_post()函数中指定一下文章所属分类id便能使代码完全有效。
下面是完整的代码:
复制代码 代码如下:
$categories = get_the_category();
$categoryids = array();
foreach ($categories as $category) {
array_push($categoryids, $category->term_id);
}
$categoryids = implode(,, $categoryids);
?>
打开主题目录下的文章页single.php,在要显示的位置添加代码,保存文件即可。以上这篇wordpress 单页面上一页下一页的实现方法【附代码】就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。