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

如何为文章中WooCommerce区块的外部产品添加target="_blank"属性

解决WooCommerce Products by Tag区块外部产品按钮添加target="_blank"及修改文本问题

问题分析

你之前的代码无效核心原因有两点:

  • 没有将函数挂接到WooCommerce对应的钩子上,导致代码从未被执行
  • 函数内部使用了过时属性(如$product->id),且未正确获取原按钮的变量(如$quantity、$class)

正确解决方案

使用WooCommerce官方提供的woocommerce_loop_add_to_cart_link钩子来修改按钮链接,同时实现添加target="_blank"和自定义按钮文本的需求。

方法一:直接修改现有链接(推荐)

这种方式无需重新构建整个按钮HTML,只需替换目标属性和文本,兼容性更好:

function modify_external_product_button( $link, $product ) {
    // 仅处理外部类型产品
    if ( $product->is_type( 'external' ) ) {
        // 添加target="_blank"属性
        $link = str_replace( 'rel="nofollow"', 'rel="nofollow" target="_blank"', $link );
        
        // 自定义按钮文本,替换成你需要的内容
        $custom_button_text = '前往外部店铺';
        $link = str_replace( esc_html( $product->add_to_cart_text() ), esc_html( $custom_button_text ), $link );
    }
    return $link;
}
// 将函数挂接到钩子,优先级10,传递2个参数
add_filter( 'woocommerce_loop_add_to_cart_link', 'modify_external_product_button', 10, 2 );

方法二:重新构建按钮HTML

如果你需要完全自定义按钮结构,可以用这种方式,注意保留原有的类和属性:

function custom_external_product_button( $link, $product ) {
    if ( $product->is_type( 'external' ) ) {
        // 获取原按钮的默认类和数量(兼容区块样式)
        $class = isset( $GLOBALS['product'] ) ? 'wp-block-button__link add_to_cart_button external' : 'add_to_cart_button external';
        $quantity = 1;

        // 自定义按钮文本
        $custom_text = '查看外部商品';

        // 重新构建按钮HTML
        $link = sprintf(
            '<a href="%s" data-quantity="%s" class="%s" data-product_id="%s" data-product_sku="%s" aria-label="%s" rel="nofollow" target="_blank">%s</a>',
            esc_url( $product->add_to_cart_url() ),
            esc_attr( $quantity ),
            esc_attr( $class ),
            esc_attr( $product->get_id() ), // 使用get_id()替代过时的id属性
            esc_attr( $product->get_sku() ),
            esc_html( sprintf( __( 'Add %s to cart', 'woocommerce' ), $product->get_name() ) ),
            esc_html( $custom_text )
        );
    }
    return $link;
}
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_external_product_button', 10, 2 );

使用说明

将上述代码添加到你的WordPress主题的functions.php文件中,或者使用自定义代码插件(如Code Snippets)来添加,避免主题更新时丢失代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:09:28