WooCommerce手动触发某些产品的新订单电子邮件

时间:2017-04-11 15:46:59

标签: woocommerce

请我发现此代码作为WooCommerce的解决方案新订单电子邮件手动触发某些产品,但我不知道将此代码放在functions.php的确切位置,或者谢谢。

/**
 * Modified from https://www.skyverge.com/blog/add-woocommerce-email-recipients-conditionally/
 * 
 * Add another email recipient for admin New Order emails if a product from a specific category or with a specific tag is ordered
 *
 * @param string $recipient a comma-separated string of email recipients (will turn into an array after this filter!)
 * @param \WC_Order $order the order object for which the email is sent
 * @return string $recipient the updated list of email recipients
 */
function sv_conditional_email_recipient( $recipient, $order ) {
    // Bail on WC settings pages since the order object isn't yet set yet
    // Not sure why this is even a thing, but shikata ga nai
    $page = $_GET['page'] = isset( $_GET['page'] ) ? $_GET['page'] : '';
    if ( 'wc-settings' === $page ) {
        return $recipient; 
    }

    // just in case
    if ( ! $order instanceof WC_Order ) {
        return $recipient; 
    }
    $items = $order->get_items();

    // check if product from category or with tag is in order
    foreach ( $items as $item ) {
        $product = $order->get_product_from_item( $item );
        $args = array('orderby' => 'name', 'order' => 'ASC', 'fields' => 'names');
        $product_cats = wp_get_post_terms( $product->get_id, 'product_cat', $args ); // could swap product_cat for product_tag
        // add our extra recipient if there's a product from the category with slug "dieta" - commas needed!
        // we can bail if we've found one, no need to add the recipient more than once
        if ( $product && in_array( "dieta", $product_cats ) ) {
            $recipient .= ', notify@example.com';
            return $recipient;
        }
    }

    return $recipient;
}
add_filter( 'woocommerce_email_recipient_new_order', 'sv_conditional_email_recipient', 10, 2 );

1 个答案:

答案 0 :(得分:0)

我对此进行编码并且可以在我的网站上运行,不要忘记将the_name_of_the_cat替换为类别名称,并将first_email@domain.com,second_email@domain.com替换为两封电子邮件。

function change_email_recipient_depending_of_cat ( $recipient, $order ) {
    global $woocommerce;
    $items = $order->get_items();
    foreach ( $items as $item ) {
        $product_id = $item['product_id'];
        if ( has_term( 'the_name_of_the_cat', 'product_cat', $product_id ) ) {
            $recipient = 'first_email@domain.com,second_email@domain.com';
        }
        return $recipient;
    }
}
add_filter( 'woocommerce_email_recipient_new_order', 'change_email_recipient_depending_of_cat', 10, 2 );