Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Shortcode that echos the sum of subpages WordPress

  • SOLVED

I need a simple shortcode that echos the sum of subpages of a Parent page not including the parent.

<strong>Example:</strong>
Parent Page = Energy Drink
Sub Pages = Red Bull, Monster, Nittro, Rockstar.

The Shortcode would simply echo "4"

<strong>Usage:</strong> There are [subpages id=24] pages within the Energy drink Category.

Thank you

Answers (2)

2010-12-18

Andrzej answers:

function sum_subpages_shortcode($atts, $content = null) {
extract(shortcode_atts(array("id" => false), $atts));
if ( !$id ) return false;
global $post;
$myposts = get_posts(array('post_type' => 'page', 'post_parent' => (int) $id, 'post_status' => 'published'));
wp_reset_query();
return sizeof($myposts);
}
add_shortcode("subpages", "sum_subpages_shortcode");


Andrzej comments:

or this code would automaticly use current post ID if nothing is specified:

function sum_subpages_shortcode($atts, $content = null) {
extract(shortcode_atts(array("id" => false), $atts));
global $post;
if ( !$id ) $id = $post->ID;
$myposts = get_posts(array('post_type' => 'page', 'post_parent' => (int) $id, 'post_status' => 'published'));
wp_reset_query();
return sizeof($myposts);
}
add_shortcode("subpages", "sum_subpages_shortcode");

2010-12-18

Joachim Kudish answers:

Here's another way that is slightly more efficient but very similar to that above :

function sum_subpages($atts) {
$atts = extract(shortcode_atts(array('id'=>''),$atts));
$subpages = get_pages(array('child_of' => $id, 'parent' => $id, 'hierarchical' => 0));
$amount = count($subpages);
return $amount;
}
add_shortcode('subpages','sum_subpages');


This won't list grand-parent pages. If you DO want to list them then all you have is change this line:
$subpages = get_pages(array('child_of' => $id, 'parent' => $id, 'hierarchical' => 0));


to $subpages = get_pages(array('child_of' => $id, 'hierarchical' => 0));

This code goes into your theme's functions.php obviously or into a plugin file