根据购物车中的当前产品类型在 WooCommerce 中禁用新帐户电子邮件通知

问题描述

对于使用 learndash 的客户,我偶然发现了一个非常不方便的功能。这种电子学习集成要求客户被迫在结账时创建一个帐户并收到有关它的电子邮件。对于已售出的课程,这很好,但是,该客户还想出售其他东西。

因此,如果没有强制创建帐户,此插件将无法运行,因此当购买的产品类型不是“课程”时,我想删除给客户的新帐户电子邮件

到目前为止我有

function disable_account_creation_email( $email_class ) {
    $order = wc_get_order();
    $product_type = '';
    if (!empty($order)){
        foreach ($order->get_items() as $item_key => $item){
        $product = $item->get_product();
        $product_type   .= $product->get_type();
        }
        if (stripos($product_type,'course') ===false){
    remove_action( 'woocommerce_created_customer_notification',array( $email_class,'customer_new_account' ),10,3 );
        }
    }
}
add_action( 'woocommerce_email','disable_account_creation_email' );

然而,它不起作用。

有什么建议吗?

解决方法

您当前的代码中有多个错误

您可以使用 woocommerce_email_enabled_customer_new_account 过滤器钩子。

  • 检查结帐/购物车页面
  • 此答案检查产品是否属于 simple 类型 - 替换为您自己的产品类型
  • 在 WooCommerce 5.0.0 中测试并且可以工作,通过添加到代码中的注释标签进行解释

  1. 使用它来检查购物车中1的产品是否属于某种类型
function filter_woocommerce_email_enabled_customer_new_account( $enabled,$user,$email ) { 
    // Only run in the Cart or Checkout pages
    if ( is_cart() || is_checkout() ) {
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            // Get product
            $product = $cart_item['data'];
                    
            // Get product type
            $product_type = $product->get_type();
                    
            // Compare
            if ( $product_type == 'simple' ) {
                // Enabled = false,break loop
                $enabled = false;
                break;
            }
        }
    }
    
    return $enabled;
}
add_filter( 'woocommerce_email_enabled_customer_new_account','filter_woocommerce_email_enabled_customer_new_account',10,3 );

  1. 如果购物车中的所有产品都属于某种类型,请使用以下内容
function filter_woocommerce_email_enabled_customer_new_account( $enabled,$email ) { 
    // Only run in the Cart or Checkout pages
    if ( is_cart() || is_checkout() ) {
        // Set flag
        $flag = true;
                
        // Loop through cart items
        foreach ( WC()->cart->get_cart() as $cart_item ) {
            // Get product
            $product = $cart_item['data'];
                    
            // Get product type
            $product_type = $product->get_type();
                    
            // Compare
            if ( $product_type != 'simple' ) {
                $flag = false;
            }
        }
                
        // If flag is true
        if ( $flag ) {
            // Enabled = false
            $enabled = false;   
        }
    }
    
    return $enabled;
}
add_filter( 'woocommerce_email_enabled_customer_new_account',3 );