PHP: Use the WordPress API to Build a Shortcode to List Subpages
We’re working on quite a complex implementation for an enterprise client right now. The site is being built in WordPress but has a ton of bells and whistles. Often, when I’m doing this type of work, I like to save the custom code for repurposing later on other sites. In this case, I thought it was such a useful function, I wanted to share it with the world. We’re using the Avada WordPress theme with the Fusion Page Builder as a parent theme, and deploying quite a bit of custom code in our child theme.
WordPress already has a couple of functions in its API that can be used to list subpages, like wp_list_pages and get_pages. The problem is that they don’t return enough information if you’re hoping to dynamically create a list with a bunch of information.
For this customer, they wanted to post job descriptions and have the list of job openings automatically get generated in descending order by their publish date. They also wanted to display an excerpt of the page.
So, first, we had to add excerpt support to the page template. In functions.php for their theme, we added:
add_post_type_support( 'page', 'excerpt' );
Then, we needed to register a custom shortcode that would generate the list of subpages, links to them, and the excerpt for them. Do do this, we have to use the WordPress Loop. In functions.php, we added:
// List Subpages in a List function dknm_list_child_pages( $atts, $content = "" ) { global $post; $atts = shortcode_atts( array( 'ifempty' => 'No Records', 'aclass' => '' ), $atts, 'list_subpages' ); $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => $post->ID, 'orderby' => 'publish_date', 'order' => 'DESC', ); $parent = new WP_Query( $args ); if ( $parent->have_posts() ) { $string .= $content.'<ul>'; while ( $parent->have_posts() ) : $parent->the_post(); $string .= '<li><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; } else { $string = '<p>'.$atts['ifempty'].'</p>'; } wp_reset_postdata(); return $string; } add_shortcode('list_subpages', 'dknm_list_child_pages');
Now, the shortcode can be implemented throughout the site to show the child pages with a link and excerpt. Usage:
[list_subpages aclass="button" ifempty="Sorry, we currently don't have any job openings."]<h3>List of Jobs</h3>[/list_subpages]
The result is a nice, clean unordered list of the published jobs, which are child pages under their career page.
If there were no jobs published (no child pages), it will publish:
Sorry, we currently don’t have any job openings.
If there were jobs published (child pages), it will publish:
List of Jobs:
- Latest Child Page – Excerpt from the Child Page
- Next Child Page – Excerpt from the Child Page
- Next Child Page – Excerpt from the Child Page