Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
1  
Can you edit your question to include your code? –  s_ha_dum Feb 20 '13 at 15:48
add comment

1 Answer

up vote 0 down vote accepted

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

Your Answer

 
discard

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.