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

优化输出JSON数据的代码:改进add_price_calculate_tour()函数

优化后的旅游产品价格JSON注入PHP代码

我来帮你优化这段用于传递旅游产品价格到前端的PHP代码,主要从代码健壮性、WordPress最佳实践和安全性三个维度调整:

优化点说明

  • 避免全局变量依赖:原代码直接使用global $post,如果函数在非循环/单页环境下执行会报错,我们增加了对$post的存在性检查
  • 增强产品有效性验证:先判断wc_get_product()的返回值是否有效,避免后续调用产品方法时出现致命错误
  • 价格数据兜底处理:给价格元数据设置默认值,防止元数据缺失导致float转换失败
  • 安全的JSON生成:利用WordPress内置的JSON编码功能,避免手动拼接JSON可能带来的XSS风险
  • 清晰的代码结构:拆分变量定义,增加注释提升可读性

优化后的完整代码

function add_price_calculate_tour() {
    // 避免直接依赖全局$post,先检查是否存在
    if ( ! isset( $GLOBALS['post'] ) ) {
        return;
    }

    $post_id = get_the_ID();
    $product = wc_get_product( $post_id );

    // 验证产品是否有效且为指定类型
    if ( ! $product || ! $product->is_type( 'tour_booking' ) ) {
        return;
    }

    // 获取价格元数据,设置默认值避免空值问题
    $price_adult = (float) get_post_meta( $post_id, '_regular_price', true ) ?: 0.0;
    $price_child = (float) get_post_meta( $post_id, 't_children_price', true ) ?: 0.0;

    // 直接传递数组,WordPress会自动安全编码为JSON
    wp_add_inline_script(
        'twentyseventeen-global',
        sprintf( 'var tour = %s;', wp_json_encode( [
            'priceAdult' => $price_adult,
            'priceChild' => $price_child
        ] ) ),
        'before'
    );
}
// 记得将函数挂在wp_enqueue_scripts钩子上(确保目标脚本已注册)
add_action( 'wp_enqueue_scripts', 'add_price_calculate_tour' );

额外提示

  • 如果你不确定twentyseventeen-global脚本是否已经注册,可以先用wp_script_is( 'twentyseventeen-global', 'registered' )做前置检查
  • 如果需要在前端更安全地使用这个变量,建议包裹在IIFE里避免全局变量污染:
(function() {
    // 这里写使用tour变量的逻辑
    console.log('成人价格:', tour.priceAdult);
})();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:15:07