Last active
September 2, 2016 20:48
-
-
Save timothyjensen/196d6a5dc69d276de12363beea925635 to your computer and use it in GitHub Desktop.
Renders buttons that link to a page's closest siblings
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Calls the page link functions on pages that are descendants of $greatest_ancestor | |
* | |
* @param int $greatest_ancestor The ID of the top level ancestor | |
*/ | |
function tj_page_navigation_links( $greatest_ancestor ) { | |
//* Get the ancestors of the current page | |
$page_ancestors = get_post_ancestors( get_the_ID() ); | |
//* Return early if not a descendant of $page_ancestors | |
if ( ! in_array( $greatest_ancestor, $page_ancestors) ) | |
return; | |
$args = array( | |
'post_parent' => $page_ancestors[0], | |
'post_status' => 'publish', | |
'orderby' => 'menu_order', | |
'order' => 'ASC', | |
); | |
$siblings = array_keys( get_children( $args ) ); | |
$position = array_search( get_the_ID(), $siblings ); | |
tj_prev_sibling_link( $siblings, $position ); | |
tj_next_sibling_link( $siblings, $position ); | |
} | |
/** | |
* Renders the Prev: Page button | |
* | |
* @param array $siblings All children of $greatest_ancestor | |
* @param int $position Position of the current page among its siblings | |
*/ | |
function tj_prev_sibling_link( $siblings, $position ) { | |
if ( get_the_ID() == $siblings[0] ) | |
return; | |
//* Render a button that links to the previous sibling page. | |
$prev_sibling_permalink = get_the_permalink( $siblings[$position-1] ); | |
$prev_sibling_title = get_the_title( $siblings[$position-1] ); | |
printf( '<a class="%s" href="%s">%s</a>', 'button prev', $prev_sibling_permalink, 'Prev: ' . $prev_sibling_title ); | |
} | |
/** | |
* Renders the Next: Page button | |
* | |
* @param array $siblings All children of $greatest_ancestor | |
* @param int $position Position of the current page among its siblings | |
*/ | |
function tj_next_sibling_link( $siblings, $position ) { | |
if ( get_the_ID() == end( $siblings) ) | |
return; | |
//* Render a button that links to the next sibling page. | |
$next_sibling_permalink = get_the_permalink( $siblings[$position+1] ); | |
$next_sibling_title = get_the_title( $siblings[$position+1] ); | |
printf( '<a class="%s" href="%s">%s</a>', 'button next', $next_sibling_permalink, 'Next: ' . $next_sibling_title ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment