仅修改发送给管理员的WooCommerce新订单通知CSS样式
问题描述
我希望仅修改发送给管理员的新订单通知的表头表格样式,客户邮件不受影响。我使用的代码如下,但似乎无法正常运行,恳请提供帮助。
add_filter( 'woocommerce_email_styles', 'add_css_to_new_order_email', 9999, 2 ); function add_css_to_new_order_email( $css, $email ) { if ( $email->id == 'new_order' && $email->recipient == 'admin' ) { $css .= ' #header_wrapper { background-color: #000!important; } h1 { color: #000!important; } '; } return $css; }
解决方案
你的代码失效原因是**$email->recipient == 'admin'的判断逻辑不准确**:站点管理员的收件邮箱通常不是字符串admin,而是实际的邮箱地址(比如admin@yourdomain.com);如果有多个管理员收件人,这个严格相等的判断也会失效。
以下是两种可靠的修复方案:
方案1:通过用户权限判断(后台触发场景适用)
利用current_user_can('manage_options')判断触发邮件的用户是否具备管理员权限,适合后台生成的新订单通知:
add_filter( 'woocommerce_email_styles', 'custom_admin_new_order_email_styles', 9999, 2 ); function custom_admin_new_order_email_styles( $css, $email ) { // 仅针对新订单邮件,且触发用户为管理员 if ( $email->id === 'new_order' && current_user_can( 'manage_options' ) ) { $css .= ' #header_wrapper { background-color: #000 !important; } h1 { color: #000 !important; } '; } return $css; }
方案2:通过管理员邮箱匹配(全场景适配)
获取站点配置的管理员邮箱,检查收件人列表中是否包含该邮箱,适配所有发送给管理员的场景(包括多收件人):
add_filter( 'woocommerce_email_styles', 'custom_admin_new_order_email_styles', 9999, 2 ); function custom_admin_new_order_email_styles( $css, $email ) { $admin_email = get_option( 'admin_email' ); // 仅针对新订单邮件,且收件人包含管理员邮箱 if ( $email->id === 'new_order' && strpos( $email->recipient, $admin_email ) !== false ) { $css .= ' #header_wrapper { background-color: #000 !important; } h1 { color: #000 !important; } '; } return $css; }
关键说明
- 保持优先级
9999确保自定义样式能覆盖WooCommerce默认邮件样式 - 使用
!important强制覆盖原有CSS规则,避免样式被默认规则覆盖
内容的提问来源于stack exchange,提问作者Acephalia
相关产品推荐
相关产品推荐

