WooCommerce商品列表页替换商品链接为自定义链接按钮重复问题
问题根源
你的代码存在两处核心逻辑错误:
is_product()是WooCommerce内置条件标签,仅用于判断当前页面是否为单个商品详情页,返回值为布尔类型(true/false),你将它和商品ID做相等判断本身就不成立。- 两个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
相关产品推荐
相关产品推荐

