如何不修改插件文件移除WooCommerce的woocommerce_email_header动作钩子
解决WooCommerce外部移除
woocommerce_email_header动作的问题 问题核心在于WC_Emails采用单例模式,woocommerce_email_header动作是绑定在类的实例对象上的,而非静态方法,所以直接用类名WC_Emails调用remove_action无效。
正确解决方案
- 选对钩子时机:必须在WooCommerce加载完成、动作已经添加之后执行移除操作,推荐用
woocommerce_loaded钩子,并设置较高的优先级(比如20,确保晚于动作添加的时机)。 - 获取WC_Emails的单例实例:通过
WC_Emails::instance()拿到实际绑定动作的对象,再用这个对象执行移除。
代码示例:
add_action( 'woocommerce_loaded', 'remove_woocommerce_default_email_header', 20 ); function remove_woocommerce_default_email_header() { // 获取WC_Emails的单例实例 $wc_emails_instance = WC_Emails::instance(); // 移除绑定在实例上的email_header动作 remove_action( 'woocommerce_email_header', array( $wc_emails_instance, 'email_header' ) ); }
可选:替换自定义邮件头部
如果需要替换默认头部,移除后可以添加自己的回调:
add_action( 'woocommerce_email_header', 'custom_woocommerce_email_header', 10, 2 ); function custom_woocommerce_email_header( $email_heading, $email ) { // 这里写你的自定义头部内容,比如: echo '<div class="custom-email-header">'; echo '<h2 style="color:#222;">' . esc_html( $email_heading ) . '</h2>'; echo '</div>'; }
内容的提问来源于stack exchange,提问作者Milica
相关产品推荐
相关产品推荐

