Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
WordPress: Register a shortcode to list child pages on a parent page
<php
// Turn on excerpt support for pages by enabling them in your themes functions.php file
add_post_type_support( 'page', 'excerpt' );
/* Add the below function to your theme's functions.php file
** This has more capabilities than get_pages and wp_list_pages
** Usage: [list_subpages aclass="button" ifempty="Sorry, we currently don't have any job openings."]<h3>List of Jobs</h3>[/list_subpages]
*/
// List Subpages in a List
function dk_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', 'dk_list_child_pages');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment