0

当订单仅包含特定类别的产品时,我试图在订单完成时触发两个操作。这些产品的重量为 0 很容易识别,这使我可以通过它们的运输方式识别这些订单。我使用此方法两次,更改管理员电子邮件的收件人并自动完成订单。

当我测试时,它们都可以正常工作。但是 IRL,虽然电子邮件更改始终由运输方式触发,但许多订单并未“自动完成”。这给我的印象是,虽然 woocommerce_email_recipient_new_order 始终被触发,但 woocommerce_thankyou 不是。我不知道为什么,这对我的客户来说是一个真正的问题。

知道是什么原因造成的吗?

(完全披露:这个话题我已经提过了,但是因为函数内部的选单机制比较复杂,所以回答的人肯定代码的失败来自函数而不是woocommerce_thankyou没有正确触发。我觉得有了这些非常简单的函数,毫无疑问,问题发生在 custom_woocommerce_auto_complete_order 函数本身之外。)

两种功能,一个总是正确触发,一个不能:

/**
     * Change email recipient for admin New Order emails when the order only has products from the 'abo' category
     *
     * @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
     */

    add_filter( 'woocommerce_email_recipient_new_order', 'dada_conditional_email_recipient', 10, 2 );

    function dada_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; 
        }

            $shipping_method = $order->get_shipping_method(); 

        if ( $shipping_method == 'Abonnement' ) {
            $recipient = 'newrecip@mail.fr';
        }
        else {
            $recipient = 'oldrecip@mail.fr';
        }
        return $recipient;
    }


    /**
     * Autocomplete orders with only an 'abo' product
     */

    add_action( 'woocommerce_thankyou', 'custom_woocommerce_auto_complete_order' );

    function custom_woocommerce_auto_complete_order( $order_id ) { 
    if ( ! $order_id ) {
        return;
    }

    $order = wc_get_order( $order_id );

    $shipping_method = $order->get_shipping_method(); 

    if ( $shipping_method == 'Abonnement' ) {
        $order->update_status( 'completed' );
    }
}
4

0 回答 0