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

如何在WooCommerce中定位特定可变产品,仅显示加购按钮下方自定义消息

解决WooCommerce特定可变产品显示自定义消息的问题

要实现仅在特定可变产品的「加入购物车」按钮下方显示自定义消息,只需在原有代码中增加产品ID匹配判断即可,修改后的代码如下:

add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 10, 0 );
function custom_product_message() {
    global $product;

    // 替换为你目标产品的ID
    $target_product_id = 123;

    // 仅对指定ID的可变产品生效
    if ( ! $product->is_type( 'variable' ) || $product->get_id() !== $target_product_id ) {
        return;
    }

    echo '<div class="woo_variable_custom_message">Hello</div>';
}

代码说明:

  • $target_product_id:替换为你需要显示自定义消息的可变产品ID(可在WooCommerce产品编辑页面的URL中找到,例如post=123中的123)
  • 判断逻辑同时检查产品类型(可变产品)和产品ID,确保仅目标产品触发消息
  • 保留原有代码结构,仅增加精准定位的条件

如果需要对多个特定可变产品生效,可以使用数组判断:

add_action( 'woocommerce_after_add_to_cart_button', 'custom_product_message', 10, 0 );
function custom_product_message() {
    global $product;

    // 替换为你需要的多个产品ID
    $target_product_ids = [123, 456, 789];

    if ( ! $product->is_type( 'variable' ) || ! in_array( $product->get_id(), $target_product_ids ) ) {
        return;
    }

    echo '<div class="woo_variable_custom_message">Hello</div>';
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 21:40:26