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

如何为WooCommerce邮件模板特定元字段添加CSS样式

解决方案

方法1:修改子主题邮件模板,给目标区域添加包裹容器

你已经将邮件模板复制到子主题,直接在模板里把woocommerce_email_order_meta钩子的调用用一个带自定义CSS类的容器包裹,就能精准定位该区域的样式:

修改模板中的对应代码:

// 替换原有的do_action调用
<div class="custom-order-meta-section">
    <?php do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email ); ?>
</div>

接着在子主题的functions.php中添加自定义邮件CSS:

add_filter( 'woocommerce_email_styles', 'custom_order_meta_email_styles', 10, 2 );
function custom_order_meta_email_styles( $css, $email ) {
    // 针对自定义容器内的p标签设置样式
    $css .= '
        .custom-order-meta-section p {
            font-size: 14px;
            font-weight: 600;
            color: #333333;
            margin: 0 0 10px;
        }
    ';
    return $css;
}

方法2:通过钩子替换默认的订单元数据输出

如果不想修改模板,可以移除WooCommerce默认的order_meta回调,自定义输出结构:

在子主题的functions.php中添加:

// 移除默认的订单元数据输出动作
remove_action( 'woocommerce_email_order_meta', array( WC()->mailer()->emails['WC_Email'], 'order_meta' ), 10 );

// 添加自定义的订单元数据输出
add_action( 'woocommerce_email_order_meta', 'custom_email_order_meta_output', 10, 4 );
function custom_email_order_meta_output( $order, $sent_to_admin, $plain_text, $email ) {
    if ( $plain_text ) {
        // 纯文本邮件保持默认格式
        wc_get_template( 'emails/plain/email-order-meta.php', array(
            'order' => $order,
            'sent_to_admin' => $sent_to_admin,
            'plain_text' => $plain_text,
            'email' => $email
        ) );
    } else {
        // HTML邮件输出带自定义类的包裹容器
        echo '<div class="custom-order-meta-section">';
        wc_get_template( 'emails/email-order-meta.php', array(
            'order' => $order,
            'sent_to_admin' => $sent_to_admin,
            'plain_text' => $plain_text,
            'email' => $email
        ) );
        echo '</div>';
    }
}

之后同样使用方法1中的woocommerce_email_styles过滤器添加CSS样式即可。

注意事项

  • 确保子主题的邮件模板路径正确,通常为your-child-theme/woocommerce/emails/[对应模板文件名].php
  • 纯文本邮件无需样式设置,代码中已针对$plain_text做判断,保留默认纯文本格式
  • 可根据需求自行调整CSS中的字体大小、粗细及颜色值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 05:25:37