您可以尝试以下操作:
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>";
}
这将在短代码内容的末尾添加总和。
Usage example:
您可以在编辑器中尝试以下操作:
[sumsc][stat1 val="usa"] [stat2 val="europe"] [stat3 val="china"] [stat4 val="africa"][/sumsc]
Edit: 上面的函数对短代码名称中的索引求和,而不是对短代码值求和-我想我误解了这个问题;-)
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>";
}