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

如何在WooCommerce商品页添加自定义按钮,不同商品对应不同链接?

在WooCommerce商品页添加不同链接的自定义按钮

要在加入购物车表单前添加自定义按钮,同时给不同商品配置对应链接,你可以参考下面的实现方式:

优化后的代码

你原本的代码已经能实现单个商品的按钮添加,若要支持多商品不同链接,用数组统一管理商品ID与对应信息会更便于维护:

add_action( 'woocommerce_before_add_to_cart_form', 'custom_product_link_button' );
function custom_product_link_button() {
    global $product;
    if ( ! $product ) return;

    // 按需修改:商品ID、目标链接、按钮文字的映射关系
    $product_links = array(
        149685 => array(
            'url'   => '你的目标链接',
            'text'  => 'Our Links'
        ),
        12345  => array(
            'url'   => '你的目标链接',
            'text'  => '查看详情'
        ),
        67890  => array(
            'url'   => '你的目标链接',
            'text'  => '更多资源'
        )
    );

    // 匹配当前商品ID,存在对应配置则输出按钮
    if ( isset( $product_links[ $product->get_id() ] ) ) {
        $link_data = $product_links[ $product->get_id() ];
        echo '<a class="button primary is-small box-shadow-4 box-shadow-2-hover" style="border-radius: 10px; background-color:#FFDB58 !important; color:black;" target="_blank" href="' . esc_url( $link_data['url'] ) . '">' . esc_html( $link_data['text'] ) . '</a>';
    }
}

代码说明

  • 借助woocommerce_before_add_to_cart_form钩子,确保按钮精准显示在加入购物车表单的前方
  • 数组$product_links集中管理所有需要添加按钮的商品信息,后续新增/修改商品配置只需调整这个数组,无需重复编写判断逻辑
  • 使用esc_url()和esc_html()对链接与文本进行转义,提升代码安全性,避免XSS风险
  • 保留了你原本设置的按钮样式类与自定义CSS,保证按钮外观符合预期

使用步骤

  1. 将代码添加到当前主题的functions.php文件中,或通过自定义代码插件(如Code Snippets)导入
  2. 根据实际需求,修改$product_links数组内的商品ID、目标链接和按钮文字

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:25:09