25% off ProSNIPC25OFF

Child Pages List Shortcode

Shortcode [scseed_child_pages] that lists the immediate sub-pages of the current (or a specified) page.

PHPby SnipCraft
php
<?php
// [scseed_child_pages parent="" orderby="menu_order" order="ASC" show_thumb="false" show_desc="false"]
add_shortcode( 'scseed_child_pages', 'scseed_child_pages_shortcode' );
if ( ! function_exists( 'scseed_child_pages_shortcode' ) ) {
    function scseed_child_pages_shortcode( $atts ) {
        $atts = shortcode_atts( [
            'parent'    => '',
            'orderby'   => 'menu_order',
            'order'     => 'ASC',
            'show_thumb' => false,
            'show_desc'  => false,
        ], $atts, 'scseed_child_pages' );

        $parent_id = ! empty( $atts['parent'] ) ? absint( $atts['parent'] ) : get_the_ID();

        $allowed_order = [ 'ASC', 'DESC' ];
        $order = in_array( strtoupper( $atts['order'] ), $allowed_order, true )
            ? strtoupper( $atts['order'] ) : 'ASC';

        $pages = get_pages( [
            'parent'      => $parent_id,
            'sort_column' => sanitize_key( $atts['orderby'] ),
            'sort_order'  => $order,
            'post_status' => 'publish',
        ] );

        if ( empty( $pages ) ) {
            return '';
        }

        $out = '<ul class="scseed-child-pages">';
        foreach ( $pages as $page ) {
            $out .= '<li class="scseed-child-pages__item">';
            if ( filter_var( $atts['show_thumb'], FILTER_VALIDATE_BOOLEAN ) && has_post_thumbnail( $page->ID ) ) {
                $out .= '<a href="' . esc_url( get_permalink( $page->ID ) ) . '">'
                    . get_the_post_thumbnail( $page->ID, 'thumbnail' ) . '</a> ';
            }
            $out .= '<a href="' . esc_url( get_permalink( $page->ID ) ) . '">'
                . esc_html( $page->post_title ) . '</a>';
            if ( filter_var( $atts['show_desc'], FILTER_VALIDATE_BOOLEAN ) && ! empty( $page->post_excerpt ) ) {
                $out .= '<p class="scseed-child-pages__excerpt">'
                    . esc_html( $page->post_excerpt ) . '</p>';
            }
            $out .= '</li>';
        }
        $out .= '</ul>';
        return $out;
    }
}
#display#hierarchy#navigation#pages#shortcode