Skip to content

Instantly share code, notes, and snippets.

@reddgr
Last active October 14, 2024 12:09
Show Gist options
  • Save reddgr/b876e34df29e99c8a1464aee98c68059 to your computer and use it in GitHub Desktop.
Save reddgr/b876e34df29e99c8a1464aee98c68059 to your computer and use it in GitHub Desktop.
Shortcode to display all child pages of a given Wordpress directory
// Shortcode to display child pages (add this to functions.php)
function list_child_pages($atts) {
$atts = shortcode_atts(array(
'parent_id' => 0,
), $atts, 'child-pages');
$args = array(
'post_type' => 'page',
'post_parent' => $atts['parent_id'],
'orderby' => 'menu_order',
'order' => 'ASC',
);
$child_pages = new WP_Query($args);
if ($child_pages->have_posts()) {
$output = '<ul>';
while ($child_pages->have_posts()) {
$child_pages->the_post();
$output .= '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>';
}
$output .= '</ul>';
} else {
$output = 'No child pages found.';
}
wp_reset_postdata();
return $output;
}
add_shortcode('child-pages', 'list_child_pages');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment