You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求可实现数值计算的WordPress短码及示例参考

WordPress 数值计算短码实现方案

以下是满足需求的px-calc短码实现代码,可直接添加到主题的functions.php文件或自定义插件中:

function px_calc_shortcode($atts) {
    // 提取短码参数并设置默认值
    $atts = shortcode_atts([
        'before' => 0,
        'operation' => '+',
        'after' => 0,
        'percentage' => false,
        'calc_suffix' => ''
    ], $atts, 'px-calc');

    // 解析嵌套短码,处理before和after参数
    $before = do_shortcode($atts['before']);
    $after = do_shortcode($atts['after']);

    // 转换为数值,避免非数值干扰
    $before = is_numeric($before) ? floatval($before) : 0;
    $after = is_numeric($after) ? floatval($after) : 0;

    // 执行基础运算
    $result = 0;
    switch($atts['operation']) {
        case '+':
            $result = $before + $after;
            break;
        case '-':
            $result = $before - $after;
            break;
        case '*':
            $result = $before * $after;
            break;
        case '/':
            // 避免除以0错误
            $result = $after != 0 ? $before / $after : 0;
            break;
        default:
            $result = 0;
    }

    // 处理后缀运算
    if (!empty($atts['calc_suffix']) && is_numeric(str_replace(['+', '-', '*', '/'], '', $atts['calc_suffix']))) {
        $suffix_expr = $result . $atts['calc_suffix'];
        @eval("\$result = $suffix_expr;");
    }

    // 处理百分比输出
    if (filter_var($atts['percentage'], FILTER_VALIDATE_BOOLEAN)) {
        $result = $result * 100;
        return number_format($result, 2) . '%';
    }

    // 返回最终结果,保留两位小数避免浮点误差
    return number_format($result, 2);
}
add_shortcode('px-calc', 'px_calc_shortcode');

参数说明

  • before:参与运算的第一个数值,支持嵌套其他短码(如获取自定义字段)
  • operation:运算符号,可选值:+、-、*、/,默认+
  • after:参与运算的第二个数值,支持嵌套其他短码
  • percentage:是否将结果转换为百分比,可选true/false,默认false
  • calc_suffix:可选后缀运算,支持在基础运算结果上追加简单表达式(如+ 50、* 2)

示例验证

  • 嵌套自定义字段计算百分比:

    [px-calc before=[wpbb post:custom_field key=nummer_1] operation='/' after=[wpbb post:custom_field key=nummer_2] percentage='true']
    

    若nummer_1为10,nummer_2为20,输出结果为50.00%

  • 直接数值计算百分比:

    [px-calc before=10 operation='/' after=20 percentage='true']
    

    输出结果:50.00%

  • 基础运算加后缀计算:

    [px-calc before=10 operation='*' after=10 calc_suffix='+ 50']
    

    输出结果:150.00

内容的提问来源于stack exchange,提问作者Bob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 21:05:16