# shortcodes inside shortcode to sum values

I have statistical shortcodes that return values

[stat1 val="usa"] [stat2 val="europe"] [stat3 val="china"] [stat4 val="africa"]

I struggle to create the shortcode that can sum the shortcode values so if

stat1=1 stat2=2 stat2=3 stat2=4 [sumsc][stat1][stat2][stat3][stat4][/sumsc] it would return the value 10

-
Can you edit your question to include your code? – s_ha_dum Feb 20 at 15:48

## 1 Answer

You can try this:

``````add_shortcode('sumsc','sumsc_func');
function sumsc_func( \$atts, \$content = null ) {
\$sum=0;
preg_match_all('/stat([0-9]+)/i', \$content, \$matches);
if(isset(\$matches[1])){
\$sum = array_sum(\$matches[1]);
}
return do_shortcode(\$content)." <div>The sum is <strong>".\$sum."</strong></div>";
}
``````

This will add the total sum at the end of the shortcode content.

Usage example:

You can try this in your editor:

``````[sumsc][stat1 val="usa"] [stat2 val="europe"] [stat3 val="china"] [stat4 val="africa"][/sumsc]
``````

Edit: The function above sums the indexes in the shortcode names, not the shortcode values - I think I misunderstood the question ;-)

Here is an updated version that sums the shortcode values:

``````add_shortcode('sumsc','sumsc_func');
function sumsc_func( \$atts, \$content = null ) {
\$sum=0;
\$content=str_replace(array("  ","] [","]["),array(" ","][","]|["),\$content);
\$codes=explode("|",\$content);
foreach(\$codes as \$code){
\$sum+=do_shortcode(\$code);
}
return " <div>The sum is <strong>".\$sum."</strong></div>";
}
``````
-
 ok I must have misunderstood him - thanks, I thought he wanted to sum the index in the shortcode names, not the shortcode values ;-) – birgire Feb 20 at 23:00