Try Tuts+ Premium, Get Cash Back!
Quick Tip: Display Excerpts of Child Pages with a Shortcode

Quick Tip: Display Excerpts of Child Pages with a Shortcode

Tutorial Details
  • Program: WordPress
  • Difficulty: Easy
  • Estimated Completion Time: 1-5 Minutes

Sometimes we have a page just for the sake of making it a parent of other pages. I’ve even seen these pages left blank! You should at least have a small paragraph for the sake of search engines and visitors alike, but what about also offering a snippet of the subpages to read similar to how your blog page does posts?

In this quick tip, we’ll create a little function that will query the page for child pages, display titles, excerpts and links if it finds any, and add it to a shortcode for use from the WordPress page editor.


Create the Function

function subpage_peek() {
	global $post;
	
	//query subpages
	$args = array(
		'post_parent' => $post->ID,
		'post_type' => 'page'
	);
	$subpages = new WP_query($args);
	
	// create output
	if ($subpages->have_posts()) :
		$output = '<ul>';
		while ($subpages->have_posts()) : $subpages->the_post();
			$output .= '<li><strong><a href="'.get_permalink().'">'.get_the_title().'</a></strong>
						<p>'.get_the_excerpt().'<br />
						<a href="'.get_permalink().'">Continue Reading →</a></p></li>';
		endwhile;
		$output .= '</ul>';
	else :
		$output = '<p>No subpages found.</p>';
	endif;
	
	// reset the query
	wp_reset_postdata();
	
	// return something
	return $output;
}

This code performs a simple query for the current page’s children.

  • Query the child pages
  • If the query returns pages, loop through them and create an output with an unordered list that includes the linked title, the excerpt, and a "Continue Reading" link
  • If the query doesn’t return anything, set the output to say that nothing was found. You could set this to whatever would be the most useful for your application.
  • Don’t forget to reset the post data!
  • Return the results rather than echo them so that it can be used as a shortcode

Create the Shortcode

add_shortcode('subpage_peek', 'subpage_peek');

Creating shortcodes out of functions is pretty simple with the built in WordPress function. You could also simply echo the function from within a template. If you really wanted to get creative, you could add it to a custom widget!


Conclusion

That’s all, folks! This is a pretty handy way of handling subpages and offering a preview to readers. Your output should look something like this:

Custom Meta Box
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: Quick Tip: Display Excerpts of Child Pages with a Shortcode | Shadowtek | Hosting and Design Solutions

  • Pingback: Display Excerpts of Child Pages in Wordpress » VC-TEL Team Blog

  • http://www.wpfix.org Wpfix

    Thanks for sharing this quick tip on display excerpts of child pages with a shortcode

    :)

  • http://megawork.de MegaWork

    Thank you very much! This really is usefull!

  • www

    how used code?

    • http://www.angelicbulldog.org.uk steve

      Add both the Function and Shortcode code to your theme functions file.

      Go to a parent page and add the shortcode. [subpage_peek]

      View parent page and should see previews of the child pages of that parent page.

  • http://www.linetoweb.com Raj Mehta

    Nice quick tip thanks for sharing this.

  • http://www.angelicbulldog.org.uk steve

    Great idea.

    Have tried this out. But only get 10 child pages in list. (same as the number of items on the news page http://www.angelicbulldog.org.uk/news which is controlled by the number of posts on blog page setting)

    How can I paginate the results to show all the child pages?

    • http://www.tammyhartdesigns.com Tammy Hart
      Author

      In the $args array add 'posts_per_page' => -1

  • http://www.tame-geek.co.uk Mark Thomson

    Nice idea this one and very useful
    Juster wondering if there was an easy way to add in the Featured Image to make it look like the a blog page?

    • http://www.tammyhartdesigns.com Tammy Hart
      Author

      You can use any of the normal functions that you would use in a normal post loop including the_post_thumbnail(). But because this example puts everything into a string before it returns it, you would need to define the post ID. So your code would look something like this: get_the_post_thumbnail($post->ID, 'thumbnail')

  • Pingback: ShortCodeを使って子ページの抜粋を表示する | 備忘録

  • Pingback: WordPress Community Roundup for the Week Ending February 11 - Charleston WordPress User Group

  • awaludin

    this is what i’m looking for

  • http://unrelatedmedia.ca Neil Davidson

    Really, really not a fan of shortcodes. The base function is fantastic though. Great work.

    If you want to make it more dynamic you could use a simple variable:

    function subpage_peek($Page_I_Think_Is_Parent_Variable)

    This way you could simply call the function wherever you need or want it and do so using any parent:

    function subpage_peek($post->ID){

    ‘post_type’ => $Page_I_Think_Is_Parent_Variable

    If you really wanted to make it useful anywhere you would add one more variable – arguments to use in a custom query.

    function subpage_peek($Page_I_Think_Is_Parent_Variable, $query_args)

    A slightly more usable and, thus, complicated variation to this is in a quick tip tutorial I wrote: Parent-Child-Page-Links

    I’ve basically done something similar to your tutorial but made it exceptionally portable with the ability to make a list of child pages anywhere based on an array of pages.

    More to the point – to do exactly what your tutorial is explaining all one would have to do is add more information in the function for displaying, not just the link, but the excerpt.

    In fact, you could make my quick tip function even more useful by returning an array of values to be accessed (post name, excerpt, images/attachments, post metas…etc)

    Great tip! Lets see more of these.

  • Leo

    Very nice function got it working without the posts per page en thumbnail.

    Can you help me i try to add
    In the $args array add ‘posts_per_page’ => -1
    But got error:
    Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ‘)’

    Same with thumbnail add
    Parse error: syntax error, unexpected T_STRING

    • Leo

      Got the thumbnail working great.

      Only the navigation is not working got remove from the error but i think it’s not working with pages?
      array looks like this now
      $args = array(
      ‘post_parent’ => $post->ID,
      ‘posts_per_page’ => -1,
      ‘post_type’ => ‘page’

      );

      If someone can help should be great to have this pagination working.

  • Pingback: Simple WordPress Functions to Enhance Your Site | Grahamblings

  • http://cjbarnaby.com Chris

    Hi, brilliant function thanks for putting this up as it has helped me a lot.

    I have one question however. I noticed that on my site here that the excerpt is running outside of the content element area and is hidden by the css …

    I am wonder how you got your excerpt to wrap to show the whole excerpt?

    Here is a link to an image of what I am talking about :

    http://www.cjbarnaby.com/example.jpg

    Thanks for all or any help.

    Cheers
    Chris

  • http://cjbarnaby.com Chris

    Ignore that previous question… i figured out that i had switched to the visual editor and it added in :

    to my page which stuffed the display inside that element.

    Maybe post this in case anyone else makes this thick mistake too

    thanks again for posting this function!

    Cheers
    Chris

  • Felixius

    Hi Tammy Hart,

    You’re awesome!

    WP newbies like me do appreciate well coded functions to learn from.

    Did I say that You’re awesome?

    Felixius

    • http://www.tammyhartdesigns.com Tammy Hart
      Author

      Aw! Thanks. I’m glad I can help. It’s funny, sometimes I think things are so simple until I realize how much they’ve helped. We really need a suggestion box here because I probably overlook a dozen good tutorial opportunities a day simple because I overlook the simplicity of things.

  • http://studiohyperset.com Quimby Melton

    Elegant and extremely helpful. Many thanks!

  • Bongo

    Hi there Tammy,

    I really like your script and have hacked it a litle to use in a slider and it is working great!

    However, it is displaying the pages in reverse chronological order like posts.

    Is it possible to make the order follow the ‘page order’ that you can set in the editing window?

    Would be a great help!

    Thanks

    Bongo

    • Bongo

      Hi Tammy,

      Never mind, I forgot how to do this… but have worked it out.

      Doh! Thanks again!

      Bongo

      //query subpages
      $args = array(
      ‘post_parent’ => $post->ID,

      ‘orderby’ => ‘menu_order’,
      ‘order’=>’ASC’,

      ‘post_type’ => ‘page’
      );

      • Samuel Moore

        Thank you, this is exactly what I needed!

  • http://www.megawork.de Mirko

    First of all: Thank You very much for this piece of code! It really does come handy in many projects!

    But now I’ve got a problem:

    ‘orderby’ => ‘random’ does not function – but I need the posts to be displayed randomly.

    Hope sbdy can help me.

    Mirko

  • doug

    This is exactly what I was looking for – THANKS!

    I am a total php newbie and was wondering if you could help me limit the length of the excerpt. It is too long as is right now. Any suggestions you have would be much appreciated.

    Thanks again.

    Doug

  • Adim

    In my home page I have listed 3 child pages with their excerpts and thumbnail images . Until here everything is working alright. But when I click the permalink and move to the full content page, thumbnail is still there. I only want the thumbnails to be present with the excerpts and when moved to the content I want this to disappear.

    Please help.

  • Paul

    Hi,

    Thank you so much for this.

    Couple of questions …

    1. Is it possible to make this go more than one level deep. I.E. so it shows child of child pages too? (and how?)

    2. Once the list goes beyond 10 posts, is there a way to make it paginate rather than your method above that shows everything?

    I’m planning on a site that has a LOT of child pages, and the list would be a mile long without this.

    Again, thank you :)

    • Brent

      Paul,

      Any luck with the Child of a Child question?

  • http://www.ellahworks.com Ellah

    Definitively, just what I am looking for.

    Simple yet powerful.

    Thank you. Kudos! :)

  • http://www.frankwaive.com Frank Waive

    would there be a way to adjust the excerpt length for the child pages without affecting the overall wordress excerpt length?

  • Ram

    Just the thing I was looking for. Thanks a ton.

    Ram

  • Sam

    Im newbie to wordpress,i have functions.php and functions folder in my /public_html/wp-content/themes/something and i have downloaded subpage_peek.zip file from ur site.but i dont know where to put this file and how to put.plz help some.

    • Ivy

      Just copy and past the code in your function.php file, including the add_shortcode code at the end. Then go to the page where you want the child page listing to be on, and type in the shortcode [subpage_peek] , including the brackets. The listing will appear in the page where you typed the shortcode.

  • http://oneplanetdesign.com Mary Bouldin

    Thanks so much! I am setting up an image shop with content from across the globe, so I have pages for continents, and pages for countries which are simply ‘placeholders’ for all of the content I am adding. Your code was a perfect editable example of what I needed.

    Anyway, just want to pass on the love! This variation of your code removes excerpts and the ‘read more’ copy and also moves titles below the thumbnail images for each page that I really needed in place.

    Yes, I know this is a simple fix, but I remember when I was even more simple than I am today. A year ago, I would have started into space and looked for another plug-in.

    Also, for simple people such as myself, don’t forget to add the start and end code for php to make this work!

    function subpage_peek() {
    global $post;
    //query subpages
    $args = array(
    ‘post_parent’ => $post->ID,
    ‘post_type’ => ‘page’
    );
    $subpages = new WP_query($args);
    // create output
    if ($subpages->have_posts()) :
    $output = ”;
    while ($subpages->have_posts()) : $subpages->the_post();
    $output .= ”.get_the_post_thumbnail().’
    ‘.get_the_title().’‘;
    endwhile;
    $output .= ”;
    else :
    $output = ‘No images found for this location. Check back soon for new product uploads!’;
    endif;
    // reset the query
    wp_reset_postdata();
    // return something
    return $output;
    }

    • Mary Bouldin

      Or, if you want this to display as a grid:

      function subpage_peek() {
      global $post;
      //query subpages
      $args = array(
      ‘post_parent’ => $post->ID,
      ‘post_type’ => ‘page’
      );
      $subpages = new WP_query($args);
      // create output
      if ($subpages->have_posts()) :
      $output = ”;
      while ($subpages->have_posts()) : $subpages->the_post();
      $output .= ”.get_the_post_thumbnail().’
      ‘.get_the_title().’‘;
      endwhile;
      $output .= ”;
      else :
      $output = ‘No images found for this location. Check back soon for new product uploads!’;
      endif;
      // reset the query
      wp_reset_postdata();
      // return something
      return $output;
      }

  • Pingback: WP Pagination for listing child pages - feed99

  • Paul

    Thanks Tammy for the code, and to Bongo for the sorting.

  • Ivy

    A big Thank You for posting this code, Tammy! Was trying to work with plugins and other codes which did not work and required many, many CSS tweaks… Your solution is simple, clean and accessed only where its needed.

  • Samuel Moore

    Thanks a lot, this really helped with my page!

  • Pingback: Showing the services | My innovations

  • http://www.facebook.com/mary.bouldin Mary Bouldin

    Quick FYI: This did NOT work on my smart phone. However – plugin SB Child List does work the same way – AND works on my phone, and I would never have known what to look for had I not seen this tutorial first.

  • http://twitter.com/yazinsai Yazin Al-Irhayim

    Love this – thank you SO much Tammy!

  • Chris

    I would like to use this with the more tag. Is this possible?

  • gstricklind

    I’m finding this doesn’t work if a child page contains (column) shortcodes. So the output on the parent ends up being the child page title and just the “Continue Reading →”. No child page excerpt. Any suggestions?

  • gstricklind

    Actually – figured it out. Add something like this

    function custom_excerpt($text = '') {
    $raw_excerpt = $text;
    if ( '' == $text ) {
    $text = get_the_content('');
    // $text = strip_shortcodes( $text );
    $text = do_shortcode( $text );
    $text = apply_filters('the_content', $text);
    $text = str_replace(']]>', ']]>', $text);
    $excerpt_length = apply_filters('excerpt_length', 55);
    $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
    $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('wp_trim_excerpt', $text, $raw_excerpt);
    }
    remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
    add_filter( 'get_the_excerpt', 'custom_excerpt' );

  • http://www.facebook.com/gabrielwebdes Gabriel Vasile

    What about get_page_children ?