List Child Items of a Hierarchical Post Type
Adds a [child_items] shortcode that lists the children of the current page or hierarchical item, such as sub-services under a service.
Opens WPIDE on
Code
add_shortcode( 'child_items', function ( $atts ) {
$atts = shortcode_atts( array( 'excerpt' => 'no' ), $atts, 'child_items' );
$post = get_post();
if ( ! $post || ! is_post_type_hierarchical( $post->post_type ) ) {
return '';
}
$children = get_posts( array(
'post_type' => $post->post_type,
'post_parent' => $post->ID,
'posts_per_page' => 100,
'orderby' => array( 'menu_order' => 'ASC', 'title' => 'ASC' ),
'no_found_rows' => true,
) );
if ( ! $children ) {
return '';
}
$html = '<ul class="child-items">';
foreach ( $children as $child ) {
$html .= '<li><a href="' . esc_url( get_permalink( $child ) ) . '">' . esc_html( get_the_title( $child ) ) . '</a>'
. ( 'yes' === $atts['excerpt'] && has_excerpt( $child ) ? '<br><span class="child-excerpt">' . esc_html( get_the_excerpt( $child ) ) . '</span>' : '' ) . '</li>';
}
return $html . '</ul>';
} );
Notes
Ordered by the Order field, then title. Add excerpt="yes" to include short descriptions.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.