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

如何将WooCommerce钩子函数转换为产品页可用短码?

没问题!把带WooCommerce钩子的函数转成Divi能用的短码其实很简单,我给你一步步拆解,结合实际例子来说明:

把WooCommerce函数转换为Divi可用的短码

短码的核心是用add_shortcode()注册回调函数,我们只需要把原函数的逻辑迁移过去,再适配短码的输出规则就行。下面分两种情况处理你提到的两个独立函数:

1. 转换带add_action的WooCommerce钩子函数

假设你原来的钩子函数是这样的(比如在产品页显示低库存提示):

add_action( 'woocommerce_single_product_summary', 'custom_low_stock_notice', 25 );
function custom_low_stock_notice() {
    global $product;
    if ( $product->is_in_stock() && $product->get_stock_quantity() < 10 ) {
        echo '<p class="low-stock-alert">仅剩 ' . $product->get_stock_quantity() . ' 件,欲购从速!</p>';
    }
}

转成短码的话,我们需要调整输出方式(短码要求返回内容而非直接echo),同时增加页面判断避免出错:

function custom_low_stock_notice_shortcode() {
    global $product;
    // 确保当前是产品页且产品对象存在
    if ( ! is_product() || ! $product ) return '';
    
    ob_start(); // 开启输出缓冲,避免直接echo打乱Divi布局
    
    if ( $product->is_in_stock() && $product->get_stock_quantity() < 10 ) {
        echo '<p class="low-stock-alert">仅剩 ' . $product->get_stock_quantity() . ' 件,欲购从速!</p>';
    }
    
    return ob_get_clean(); // 返回缓冲的内容作为短码输出
}
add_shortcode( 'low_stock_alert', 'custom_low_stock_notice_shortcode' );

2. 转换普通独立函数

假设另一个函数是获取产品的自定义字段值,比如:

function get_product_custom_tag() {
    global $product;
    if ( $product ) {
        return get_post_meta( $product->get_id(), 'product_custom_tag', true );
    }
    return '';
}

转成短码的逻辑类似,同样要注意输出安全和页面判断:

function product_custom_tag_shortcode() {
    global $product;
    if ( ! is_product() || ! $product ) return '';
    
    $custom_tag = get_post_meta( $product->get_id(), 'product_custom_tag', true );
    // 转义输出避免安全问题,同时判断值是否存在
    return $custom_tag ? '<p class="product-custom-tag">专属标签:' . esc_html( $custom_tag ) . '</p>' : '';
}
add_shortcode( 'product_custom_tag', 'product_custom_tag_shortcode' );

使用步骤

  • 把上面的代码添加到主题的functions.php文件,或者用自定义代码插件(比如Code Snippets)来添加,避免主题更新丢失代码。
  • 在Divi Builder的产品页模板中,找到「短码」模块,粘贴对应的短码(比如[low_stock_alert]或[product_custom_tag]),放到你想要展示的位置即可。

关键注意点

  • 必须用ob_start()和ob_get_clean()处理输出:短码要求返回内容,直接echo会破坏Divi的布局结构。
  • 增加is_product()判断:确保短码只在产品页生效,避免在其他页面出现错误。
  • 用esc_html()转义输出内容:防止XSS安全漏洞,这是WordPress开发的最佳实践。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:36:36