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

基于WooCommerce产品ID为各维度属性创建独立短代码

WooCommerce 产品独立维度短代码实现方案

需求概述

  • WooCommerce产品维度包含长度、宽度和高度
  • 需要基于产品ID,为每个维度属性单独创建短代码,实现单独调用展示

问题说明

查阅资料后,未找到能将产品维度拆分为三个独立短代码的现成方案,现有示例仅能整体展示维度,无法单独调用各属性。

预期使用方式

在需要展示的位置分别添加对应短代码:

  • 长度短代码:[product_dim id="35" type="length"]
  • 宽度短代码:[product_dim id="35" type="width"]
  • 高度短代码:[product_dim id="35" type="height"]

实现代码

将以下代码添加到主题的functions.php文件或自定义插件中即可实现功能:

// 注册产品维度独立短代码
function wc_product_single_dimension_shortcode( $atts ) {
    // 提取短代码参数,设置默认值
    $atts = shortcode_atts( array(
        'id'   => '', // 产品ID
        'type' => 'length' // 维度类型:length/width/height
    ), $atts, 'product_dim' );

    // 验证产品ID有效性
    if ( empty( $atts['id'] ) || ! is_numeric( $atts['id'] ) ) {
        return '';
    }

    // 获取目标产品对象
    $product = wc_get_product( $atts['id'] );

    // 检查产品是否存在
    if ( ! $product ) {
        return '';
    }

    // 根据类型获取对应维度值
    switch ( $atts['type'] ) {
        case 'width':
            $dimension_value = $product->get_width();
            break;
        case 'height':
            $dimension_value = $product->get_height();
            break;
        case 'length':
        default:
            $dimension_value = $product->get_length();
            break;
    }

    // 拼接维度值与单位并返回
    if ( ! empty( $dimension_value ) ) {
        $unit = get_option( 'woocommerce_dimension_unit' );
        return $dimension_value . $unit;
    }

    // 维度为空时返回空内容
    return '';
}
add_shortcode( 'product_dim', 'wc_product_single_dimension_shortcode' );

代码说明

  • 统一使用[product_dim]短代码,通过id指定产品ID,type指定要展示的维度类型
  • 自动读取WooCommerce后台设置的维度单位,无需手动配置
  • 若产品ID无效或对应维度为空,短代码将返回空内容,避免显示错误信息

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 17:45:11