这是一个自我Q& A。
通常在WordPress中使用页面层次结构来构建项目结构。例如,在进行投资组合网站时,这很常见:
因此,当用户在3系列页面上时,您通常希望链接到“下一个汽车制造商”。没有插件你怎么能这样做?
答案 0 :(得分:2)
这些功能允许您设置要用于确定下一页的深度。所以在问题上,用户是'3系列',因此深度为2.因此,返回的链接将是“奥迪”页面。
在你的模板中使用它(我的例子是使用图像作为链接文本):
$nextIMG = '<img src="'.get_template_directory_uri().'/images/icon-nav-right.png"/>';
echo next_project_link($nextIMG);
并将其放在functions.php中:
/*
* Next Project Link
*/
function next_project_link($html) {
global $post;
// Change this to set what depth you want the next page of
$parent_depth = 2;
$ancestors = get_post_ancestors($post);
$current_project_id = $ancestors[$parent_depth-1];
// Check for cached $pages
$pages = get_transient( 'all_pages' );
if ( empty( $transient ) ){
$args = array(
'post_type' => 'page',
'order' => 'ASC',
'orderby' => 'menu_order',
'post_parent' => $ancestors[$parent_depth],
'fields' => 'ids',
'posts_per_page' => -1
);
$pages = get_posts($args);
set_transient('all_pages', $pages, 10 );
}
$current_key = array_search($current_project_id, $pages);
$next_page_id = $pages[$current_key+1];
if( isset($next_page_id) ) {
// Next page exists
return '<a class="next-project" href="'.get_permalink($next_page_id).'">'.$html.'</a>';
}
}
/*
* Previous Project Link
*/
function previous_project_link($html) {
global $post;
// Change this to set what depth you want the next page of
$parent_depth = 2;
$ancestors = get_post_ancestors($post);
$current_project_id = $ancestors[$parent_depth-1];
// Check for cached $pages
$pages = get_transient( 'all_pages' );
if ( empty( $transient ) ){
$args = array(
'post_type' => 'page',
'order' => 'ASC',
'orderby' => 'menu_order',
'post_parent' => $ancestors[$parent_depth],
'fields' => 'ids',
'posts_per_page' => -1
);
$pages = get_posts($args);
set_transient('all_pages', $pages, 10 );
}
$current_key = array_search($current_project_id, $pages);
$prev_page_id = $pages[$current_key-1];
if( isset($prev_page_id) ) {
// Previous page exists
return '<a class="previous-project" href="'.get_permalink($prev_page_id).'">'.$html.'</a>';
}
}