php - WordPress Next Parent Page Link -
this self q&a.
often in wordpress use page hierarchy build out project structure. example, when doing portfolio sites, common:
- work
- bmw
- models
- 3-series
- 5-series
- models
- audi
- models
- a3
- a4
- models
- bmw
so, when user on 3-series page, you'd have link "next car manufacturer". how can without plugin?
these functions allow set depth want use determine next page. in question, user on '3-series', depth 2. so, link returned "audi" page.
it's used in template (my example using image link text):
$nextimg = '<img src="'.get_template_directory_uri().'/images/icon-nav-right.png"/>'; echo next_project_link($nextimg);
and place in functions.php:
/* * next project link */ function next_project_link($html) { global $post; // change set depth want next page of $parent_depth = 2; $ancestors = get_post_ancestors($post); $current_project_id = $ancestors[$parent_depth-1]; // check 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 set depth want next page of $parent_depth = 2; $ancestors = get_post_ancestors($post); $current_project_id = $ancestors[$parent_depth-1]; // check 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>'; } }
Comments
Post a Comment