You need to enable JavaScript to run this app. WooCommerce商品列表页替换商品链接为自定义链接按钮重复问题
优惠活动
大模型
产品
解决方案
定价
更多

WooCommerce商品列表页替换商品链接为自定义链接按钮重复问题

问题根源

你的代码存在两处核心逻辑错误:

  1. is_product() 是WooCommerce内置条件标签,仅用于判断当前页面是否为单个商品详情页,返回值为布尔类型(true/false),你将它和商品ID做相等判断本身就不成立。
  2. 两个if判断中都加入了|| is_shop() || is_product_category() || is_product_tag()的或条件,只要当前打开的是商品列表页、分类页、标签页,两个if条件都会直接判定为真,自然会同时输出两个按钮。

修复方案

你需要调用全局$product对象的get_id()方法,获取当前循环内对应商品的ID再做匹配,修复后代码如下:

add_action('woocommerce_after_shop_loop_item', 'add_a_custom_button', 5 );
function add_a_custom_button() {
    global $product;
    // 先判断当前页面是否为需要显示按钮的页面,不需要在详情页显示可以删掉 || is_product()
    if ( is_shop() || is_product_category() || is_product_tag() || is_product() ) :
        $current_product_id = $product->get_id();
        // 匹配对应商品ID输出对应按钮
        if ( $current_product_id == 3557 ) :
?>
<div style="margin-bottom:10px;">
    <a class="button custom-button" href="https://example.com/redirect/3557/">Buy @ Store1</a>
</div>
<?php
        elseif ( $current_product_id == 3541 ) :
?>
<div style="margin-bottom:10px;">
    <a class="button custom-button" href="https://example.com/redirect/3541/">Buy @ Store2</a>
</div>
<?php
        endif;
    endif;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 18:15:07