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

WordPress短代码无法获取WooCommerce商品价格问题排查

WooCommerce短代码获取商品价格异常问题排查与解决

问题背景

开发了一个WordPress短代码,用于通过商品ID获取WooCommerce商品价格,核心实现代码如下:

add_shortcode('db_wc_product_price', 'db_wc_product_price');

function db_wc_product_price($atts)
{
    if (!function_exists('wc_get_product') || !function_exists('get_woocommerce_currency_symbol')) return '';
$atts = shortcode_atts( array(
    'id' => null
), $atts, 'db_wc_product_price' );      
if (empty($atts['id'])) return 'no id';
    $product_id = $atts['id'];
    $ret = "id : ".$product_id;
    //return $ret;
    $product = wc_get_product($product_id); 
    //$product = wc_get_product(2571);
    if (!$product) return 'No product found';
    return get_woocommerce_currency_symbol().$product->get_price();
}

调用方式为:

[db_wc_product_price id='2571']

遇到两个异常现象:

  • 仅返回product_id时能正常显示正确值,但调用wc_get_product($product_id)时返回“No product found”,硬编码商品ID(如wc_get_product(2571))则正常
  • 使用双引号传递ID(如[db_wc_product_price id="2571"])时返回“no id”

问题原因分析

  1. ID类型不匹配:短代码接收的$atts['id']是字符串类型,而wc_get_product()要求传入整数类型的商品ID。字符串形式的ID传入后,无法正确匹配商品对象,导致返回“No product found”。
  2. 双引号解析异常:WordPress短代码的属性值解析对双引号的处理存在兼容问题,使用双引号包裹ID时,可能出现转义或解析失败,导致$atts['id']为空,触发empty($atts['id'])的判断逻辑,返回“no id”。

修复方案

1. 强制转换ID为整数类型

将获取到的ID通过absint()函数转为整数,确保传入wc_get_product()的参数类型正确。

2. 规范短代码调用格式

推荐使用单引号包裹属性值,避免双引号带来的解析问题。如果需要兼容双引号,可以在判断空值前先对ID进行trim处理,去除可能的转义字符或空格。

修复后的完整代码

add_shortcode('db_wc_product_price', 'db_wc_product_price');

function db_wc_product_price($atts)
{
    if (!function_exists('wc_get_product') || !function_exists('get_woocommerce_currency_symbol')) return '';
    
    $atts = shortcode_atts( array(
        'id' => null
    ), $atts, 'db_wc_product_price' );      
    
    // 兼容可能的空格/转义字符,同时判断空值
    $product_id = trim($atts['id']);
    if (empty($product_id)) return 'no id';
    
    // 转为整数类型
    $product_id = absint($product_id);
    
    $product = wc_get_product($product_id); 
    if (!$product) return 'No product found';
    
    return get_woocommerce_currency_symbol() . $product->get_price();
}

正确调用示例

[db_wc_product_price id='2571']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 05:48:22