如何通过自定义函数修改WooCommerce分组产品购物车验证文本
修改WooCommerce分组产品添加购物车提示文本的自定义代码方案
无需修改WooCommerce核心源码,通过添加自定义函数即可替换目标提示文本,以下是两种常见场景的实现代码:
场景1:替换分组产品页面上的默认提示文本
针对分组产品页面中子产品列表上方的提示(默认文本:Please choose a product to add to your cart…),使用翻译文本拦截钩子实现替换:
// 自定义分组产品页面提示文本 add_filter( 'gettext', 'custom_grouped_product_cart_notice', 20, 3 ); function custom_grouped_product_cart_notice( $translated_text, $text, $domain ) { // 匹配WooCommerce域下的目标文本 if ( 'woocommerce' === $domain && 'Please choose a product to add to your cart…' === $text ) { // 替换为你的自定义文本 $translated_text = '请选择一款产品加入购物车'; } return $translated_text; }
场景2:替换未选子产品时的添加购物车错误提示
当用户未选择任何子产品就点击添加到购物车按钮时,会弹出错误提示,通过验证钩子替换该提示:
// 自定义分组产品未选子产品的错误提示 add_filter( 'woocommerce_add_to_cart_validation', 'custom_grouped_product_add_to_cart_error', 10, 3 ); function custom_grouped_product_add_to_cart_error( $passed, $product_id, $quantity ) { $product = wc_get_product( $product_id ); // 检测当前产品为分组类型且未选择数量 if ( $product->is_type( 'grouped' ) && $quantity <= 0 ) { wc_clear_notices(); // 清除默认提示 // 添加自定义错误提示 wc_add_notice( '请先选择要加入购物车的产品!', 'error' ); return false; // 阻止默认添加行为 } return $passed; }
使用方法
- 将上述代码复制到当前主题的
functions.php文件末尾(建议使用子主题,避免主题更新丢失代码); - 或使用专门的自定义代码管理插件(如Code Snippets)添加代码,操作更安全便捷。
内容的提问来源于stack exchange,提问作者ttmp
相关产品推荐
相关产品推荐

