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

无需指定商品ID的WooCommerce商品标题与价格短代码需求

自动识别当前商品页面的WooCommerce短代码(无需指定ID)

你可以修改现有短代码,让它在未指定id参数时自动获取当前商品页面的商品ID,具体代码如下:

// 显示当前商品价格的短代码 [iw_product_price]
function iw_product_price_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'iw_product_price' );

    $html = '';

    // 优先使用传入的ID,没有的话获取当前页面商品ID
    $product_id = !empty($atts['id']) ? intval($atts['id']) : (is_product() ? get_the_ID() : 0);

    if( $product_id > 0 && function_exists( 'wc_get_product' ) ){
        $_product = wc_get_product( $product_id );
        $html = $_product->get_price_html();
    }
    return $html;
}
add_shortcode( 'iw_product_price', 'iw_product_price_shortcode' );

// 显示当前商品标题的短代码 [iw_product_name]
function iw_product_name_shortcode( $atts ) {
    $atts = shortcode_atts( array(
        'id' => null,
    ), $atts, 'iw_product_name' );

    $html = '';

    // 优先使用传入的ID,没有的话获取当前页面商品ID
    $product_id = !empty($atts['id']) ? intval($atts['id']) : (is_product() ? get_the_ID() : 0);

    if( $product_id > 0 && function_exists( 'wc_get_product' ) ){
        $_product = wc_get_product( $product_id );
        $html = $_product->get_title();
    }
    return $html; 
} 
add_shortcode( 'iw_product_name', 'iw_product_name_shortcode' );

关键修改说明:

  • 当用户没有指定id参数时,通过is_product()判断当前是否在商品页面,再用get_the_ID()获取当前商品的ID
  • 保留了原有指定ID的功能,兼容之前的使用方式——你仍然可以通过[iw_product_price id="123"]指定特定商品的价格
  • 修正了短代码的$atts第三个参数(原来的bartag是错误的,应该改为对应短代码的名称,确保短代码属性的优先级正确)

现在你只需要在商品页面直接使用[iw_product_price]和[iw_product_name],就能自动显示当前商品的价格和标题了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 18:23:00