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>";
}