Last active
March 25, 2018 15:30
-
-
Save hearvox/3656c50aee89cef755126e225d61f6a0 to your computer and use it in GitHub Desktop.
WordPress shortcode to list pages based on top-parent of current page (or user-specified parent).
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 | |
/* Shortcode to list page family tree, for current parent. | |
* | |
* Optional shortcode attributes: parent (ID), a depth, and title. | |
* [my_page_family_list parent="123" depth="2" title="My List Title"] | |
* | |
* @param array $atts Array of settings for wp_list_pages(). | |
* | |
* @return string $list HTML list (nested) of page-family links. | |
*/ | |
function my_page_family_list_shortcode( $atts ) { | |
if ( is_page() ) { | |
$atts = shortcode_atts( array( | |
'parent' => 0, | |
'depth' => 0, | |
'title' => '', | |
), $atts, 'hvpages' ); | |
$parent = $atts['parent']; | |
$depth = $atts['depth']; | |
$title = $atts['title']; | |
// If parent not specified, use page's parent, if any, else use page ID. | |
if ( $parent && is_int( $parent ) && get_post_type( $parent ) === 'page' ) { | |
$parent_id = $parent; | |
} else { | |
// Get top-level page ID. | |
$page_id = get_the_id(); | |
$parent_ids = get_ancestors( $page_id, 'page', 'post_type' ); | |
$parent_id = ( $parent_ids ) ? end( $parent_ids ) : $page_id; | |
$link_class = ( $page_id == $parent_id ) ? 'current_page_item' : 'page_item'; | |
} | |
$link_text = ( $title ) ? $title : get_the_title( $parent_id ); | |
$list = "<nav><h3 class=\"$link_class\">"; | |
$list .= '<a href="' . get_permalink( $parent_id ) . '"">'; | |
$list .= $link_text . '</a></h3><ul>'; | |
$list .= wp_list_pages( array( | |
'title_li' => '', | |
'child_of' => $parent_id, | |
'depth' => $depth, | |
'echo' => $false, | |
'sort_column' => 'menu_order', | |
) ); | |
$list .= '</ul></nav>'; | |
return $list; | |
} else { // Only for pages. | |
return; | |
} | |
} | |
add_shortcode( 'my_page_family_list', 'my_page_family_list_shortcode' ); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment