Last active
January 25, 2024 19:40
-
-
Save bookchiq/7573b65925579d87d8da484a1b279faf to your computer and use it in GitHub Desktop.
A shortcode to list the siblings and children of the current page (or any other hierarchical post type)
This file contains hidden or 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 | |
/** | |
* Add a shortcode to list the siblings and children of the current page. | |
* Usage: [list-siblings-and-children] | |
* | |
* @param array $atts Shortcode attributes. | |
* @return string The HTML code to render. | |
*/ | |
function yoko_list_siblings_and_children( $atts ) { | |
global $post; | |
$output = ''; | |
// Parse shortcode attributes. | |
$atts = shortcode_atts( | |
array( | |
'hide_current' => 'false', | |
), | |
$atts | |
); | |
// Check if we are on a hierarchical post type. | |
if ( is_singular() && is_post_type_hierarchical( get_post_type( $post->ID ) ) ) { | |
// Get the parent post ID. | |
$parent_id = $post->post_parent; | |
// Prepare arguments for getting sibling posts. | |
$args = array( | |
'post_type' => get_post_type( $post->ID ), | |
'posts_per_page' => -1, | |
'post_parent' => $parent_id, | |
'orderby' => 'title', | |
'order' => 'ASC', | |
'post__not_in' => 'true' === $atts['hide_current'] ? array( $post->ID ) : array(), // Conditionally exclude current post. | |
); | |
$sibling_posts = get_posts( $args ); | |
// Start the list. | |
$output .= '<ul class="siblings-and-children">'; | |
foreach ( $sibling_posts as $sibling ) { | |
// Add sibling posts with 'sibling' class. | |
$class = $sibling->ID === $post->ID ? 'current' : 'sibling'; | |
$output .= '<li class="' . esc_attr( $class ) . '"><a href="' . esc_url( get_permalink( $sibling->ID ) ) . '">' . esc_html( get_the_title( $sibling->ID ) ) . '</a>'; | |
// Check for child posts. | |
$child_args = array( | |
'post_type' => get_post_type( $post->ID ), | |
'posts_per_page' => -1, | |
'post_parent' => $sibling->ID, | |
'orderby' => 'title', | |
'order' => 'ASC', | |
); | |
$child_posts = get_posts( $child_args ); | |
if ( ! empty( $child_posts ) ) { | |
$output .= '<ul>'; | |
foreach ( $child_posts as $child ) { | |
// Add child posts with 'child' class. | |
$class = $child->ID === $post->ID ? 'current' : 'child'; | |
$output .= '<li class="' . esc_attr( $class ) . '"><a href="' . esc_url( get_permalink( $child->ID ) ) . '">' . esc_html( get_the_title( $child->ID ) ) . '</a></li>'; | |
} | |
$output .= '</ul>'; | |
} | |
$output .= '</li>'; | |
} | |
$output .= '</ul>'; | |
} | |
return $output; | |
} | |
add_shortcode( 'list-siblings-and-children', 'yoko_list_siblings_and_children' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment