Woocommerce:商品列表页加入购物车按钮跳转至商品页(不改按钮文字)
实现WooCommerce商品列表页按钮跳转至商品详情页(保留原按钮文字)
需求:让商品列表页的“加入购物车”按钮点击后跳转至对应商品详情页,同时保留已通过翻译钩子自定义的按钮文字(比如已将“Add to cart”改为“View Product”,缺货时显示“Out of Stock”等)。
原参考代码会强制替换按钮文字为固定内容,不符合需求,以下是调整后的代码:
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_loop_add_to_cart_link', 10, 2 ); function custom_loop_add_to_cart_link( $button, $product ) { // 提取原按钮中的文字内容 preg_match('/>(.*?)</', $button, $matches); $button_text = isset($matches[1]) ? $matches[1] : __('Add to cart', 'woocommerce'); // 构建跳转至商品详情页的按钮,保留原文字与样式类 $button = sprintf( '<a href="%s" class="button %s">%s</a>', esc_url( $product->get_permalink() ), esc_attr( str_replace( 'add_to_cart_button', '', wc_get_loop_add_to_cart_args()['class'] ) ), $button_text ); return $button; }
代码说明
- 通过正则从原按钮HTML中提取已有的文字内容,确保保留你通过翻译钩子设置的自定义文字;
- 重新构建按钮元素,将链接替换为商品详情页地址,保留WooCommerce默认的按钮样式类,移除原“加入购物车”的功能类;
- 搭配你已有的翻译钩子代码,即可实现保留自定义按钮文字 + 点击跳转详情页的效果。
你已有的翻译钩子代码可继续使用:
add_filter('gettext', x_translate_text , 20, 3); function x_translate_text ( $translated_text, $text, $domain ) { $translation = array ( 'Add to cart' => 'View Product', // 可添加其他需要翻译的文字 ); if( isset( $translation[$text] ) ) { return $translation[$text]; } return $translated_text; }
内容的提问来源于stack exchange,提问作者Titanium
相关产品推荐
相关产品推荐

