WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

share|improve this question
Can you edit your question to include your code? – s_ha_dum Feb 20 '13 at 15:48
up vote 0 down vote accepted

You can try this:

function sumsc_func( $atts, $content = null ) {
    preg_match_all('/stat([0-9]+)/i', $content, $matches);
        $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:

function sumsc_func( $atts, $content = null ) {
    $content=str_replace(array("  ","] [","]["),array(" ","][","]|["),$content);
    foreach($codes as $code){
    return " <div>The sum is <strong>".$sum."</strong></div>";    
share|improve this answer
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 '13 at 23:00

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.