Content Marketing

WordPress: How to List Child Pages Using A Shortcode

We’ve rebuilt the hierarchy of sites for several of our WordPress clients, and one of the things we attempt to do is organize the information efficiently. To do this, we often want to create a master page and include a menu that automatically lists the pages below it. A list of child pages, or subpages.

Unfortunately, there’s no inherent function or feature to do this within WordPress, so we developed a shortcode to add to the client’s site. Here’s how you can use the shortcode with all its variables populated within a WordPress post or page:

[listchildpages ifempty="No child pages found" order="ASC" orderby="title" ulclass="custom-ul-class" liclass="custom-li-class" aclass="custom-a-class" displayimage="yes" align="aligncenter"]

Breakdown of Usage:

  • ifempty="No child pages found": This text will be displayed if there are no child pages available.
  • order="ASC": This sorts the list of child pages in ascending order.
  • orderby="title": This orders the child pages by their title.
  • ulclass="custom-ul-class": Applies the CSS class “custom-ul-class” to the <ul> element of the list.
  • liclass="custom-li-class": Applies the CSS class “custom-li-class” to each <li> element in the list.
  • aclass="custom-a-class": Applies the CSS class “custom-a-class” to each <a> (link) element in the list.
  • displayimage="yes": This includes the featured image of each child page in the list.
  • align="aligncenter": This aligns the featured images in the center.

Insert this shortcode directly into the content area of a WordPress post or page where you want the list of child pages to appear. Remember to customize the values of each attribute to fit the design and structure of your WordPress site.

Additionally, if you’d like a short excerpt describing each page, the plugin enables excerpts on pages so that you can edit that content on the page’s settings.

List Child Pages Shortcode

function add_shortcode_listchildpages($atts, $content = "") { 
    global $post; 
    $string = '';

    $atts = shortcode_atts(array(
        'ifempty' => '<p>No Records</p>',
        'order' => 'DESC',
        'orderby' => 'publish_date',
        'ulclass' => '',
        'liclass' => '',
        'aclass' => '',
        'displayimage' => 'no',
        'align' => 'alignleft'
    ), $atts, 'listchildpages');

    $args = array(
        'post_type' => 'page',
        'posts_per_page' => -1,
        'post_parent' => $post->ID,
        'orderby' => $atts['orderby'],
        'order' => $atts['order']
    );

    $parent = new WP_Query($args);

    if ($parent->have_posts()) {
        $string .= $content.'<ul class="'.$atts['ulclass'].'">';
        while ($parent->have_posts()) : $parent->the_post();
            $string .= '<li class="'.$atts['liclass'].'">';
            $true = array("y", "yes", "t", "true");
            $showimage = strtolower($atts['displayimage']);
            if (in_array($showimage, $true)) {
                if (has_post_thumbnail($post->ID)) {
                    $image_attributes = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'thumbnail'); 
                    $string .= '<a class="'.$atts['aclass'].'" href="'.get_permalink().'" title="'.get_the_title().'">';
                    $string .= '<img src="'.$image_attributes[0].'" width="'.$image_attributes[1].'" height="'.$image_attributes[2].'" alt="'.get_the_title().'" class="'.$atts['align'].'" /></a>';
                }
            }
            $string .= '<a class="'.$atts['aclass'].'" href="'.get_permalink().'" title="'.get_the_title().'">'.get_the_title().'</a>';
            if (has_excerpt($post->ID)) {
                $string .= ' - '.get_the_excerpt();
            }
            $string .= '</li>';
        endwhile;
        $string .= '</ul>';
    } else {
        $string = $atts['ifempty'];
    }

    wp_reset_postdata();

    return $string;
}
add_shortcode('listchildpages', 'add_shortcode_listchildpages');

The function add_shortcode_listchildpages adds a custom shortcode

No Records

, which you can use within WordPress posts or pages to display a list of child pages. Here’s a breakdown of how the code works:

  1. Global Post Variable: The function begins by declaring the global variable $post, which is used to access information about the current post or page within WordPress.
  2. Shortcode Attributes: The shortcode_atts function sets up default values for the shortcode attributes. Users can override these when they insert the shortcode. Attributes include:
    • ifempty: Message to display if there are no child pages.
    • order: Order of the child pages (ASC or DESC).
    • orderby: Criteria for ordering child pages (e.g., publish_date).
    • ulclass: CSS class for the <ul> element.
    • liclass: CSS class for the <li> elements.
    • aclass: CSS class for the <a> (anchor) elements.
    • displayimage: Whether to display the featured image of the child pages.
    • align: Alignment of the featured image.
  3. Query Arguments: The function sets up a WP_Query to retrieve all child pages of the current page, sorted according to the specified attributes.
  4. Generating the List:
    • If child pages are found, the function constructs an HTML unordered list (<ul>), with each child page represented by a list item (<li>).
    • Within each list item, the function checks whether to display the featured image based on the displayimage attribute.
    • The function also creates a link to each child page using the <a> tag, and if available, adds the excerpt of the child page.
  5. Output or Default Message: If there are no child pages, the function outputs the message specified by the ifempty attribute.
  6. Reset Post Data: The wp_reset_postdata function resets the WordPress query, ensuring that the global $post object is restored to the original main query’s post.
  7. Shortcode Registration: Finally, the add_shortcode function registers listchildpages as a new shortcode, linking it to the add_shortcode_listchildpages function, making it available for use in posts and pages.

This function is useful for dynamically listing subpages on a parent page, enhancing navigation and organization within a WordPress site. I’d recommend adding it to a custom plugin if you’d like to add it to your WordPress site. Or… you can download the plugin I published.

List Child Pages Shortcode Plugin

I finally got around to pushing the code into a plugin to make it easier to install and utilize, and the List Child Pages Shortcode plugin was approved by WordPress today! Please download and install it – if you like it, provide a review!

WordPress Plugin for Listing Child Pages

Douglas Karr

Douglas Karr is CMO of OpenINSIGHTS and the founder of the Martech Zone. Douglas has helped dozens of successful MarTech startups, has assisted in the due diligence of over $5 bil in Martech acquisitions and investments, and continues to assist companies in implementing and automating their sales and marketing strategies. Douglas is an internationally recognized digital transformation and MarTech expert and speaker. Douglas is also a published author of a Dummie's guide and a business leadership book.

Related Articles

Back to top button
Close

Adblock Detected

Martech Zone is able to provide you this content at no cost because we monetize our site through ad revenue, affiliate links, and sponsorships. We would appreciate if you would remove your ad blocker as you view our site.