WordPress Shortcode To List Subpages

WordPress Shortcode To List Subpages

Share This:

Recently, I needed a way for a client to define an area in a page where subpages would be listed. Normally, this can be done just using the wp_list_pages function that WordPress provides. But that would be used within a template file, something a typical client would know nothing about. Shortcodes to the rescue!

STEP ONE

In your theme’s functions.php file, add the following code:

1
2
3
4
5
6
7
8
9
/* Create shortcode to list subpages. */
function list_subpages() {
  global $post;
  $children = wp_list_pages('title_li=&child_of='.$post->ID.'&echo=0&depth=1');
  if($children) {
  	return '<ul id="subpages">'.$children.'</ul>';
  }
}
add_shortcode('subpages', 'list_subpages');

This is what the above function does:

  • Grab the subpages of the current page
  • Only grab the first level of subpages (depth=1), don’t grab any subpages of subpages
  • If there are subpages, then display them using an unordered list
  • If there are no subpages, don’t display anything

STEP TWO

To use the shortcode, just type [subpages] anywhere in the page you want the list of subpages to display.

So then I thought, this is great! But what if they want to provide a link back to the parent page they came from? Let’s create a shortcode for that too!

STEP THREE

In your theme’s functions.php file, add the following code:

1
2
3
4
5
6
7
8
9
10
11
/* Create shortcode for parent page. */
function list_parent_page() {
  global $post;
  $parent = $post-&gt;post_parent;
  $parent_title = get_the_title($parent);
  $parent_url = get_permalink($parent);
  if($parent) {
	return '<a href="' . $parent_url . '">« Back to ' . $parent_title . '</a>';
  }
}
add_shortcode('parentpage','list_parent_page');

This is what the above function does:

  • Grab the parent page title and url of the subpage we’re currently on
  • If there is a parent page, then display a link to that parent page
  • If there is no parent page, don’t display anything

STEP FOUR

To use the shortcode, just type [parentpage] anywhere in the page you want the link to the parent page to display.

Share This:

Related Tutorials