首页 > 解决方案 > 如何检查订单是否是用户第二订单 WooCommerce 3.x

问题描述

所以我想在检查它是否是他的第二个订单之后将用户重定向到一个自定义的感谢页面。所以如果是第二个订单-->thankyou,否则-->thankyou-2。

我有这个代码:

add_action('template_redirect', 'mbm_redirect_depending_on_product_id');

function mbm_redirect_depending_on_product_id()
{

    if (!is_wc_endpoint_url('order-received') || empty($_GET['key']))
    {
        return;
    }

    $order_id = wc_get_order_id_by_order_key($_GET['key']);
    $order = wc_get_order($order_id);

    foreach ($order->get_items() as $item)
    {
        if {

            wp_redirect('/thankyou');
            exit;

        } else {
            wp_redirect('/thankyou-2');
            exit;
        }



        }
    }

}

我必须做出什么样的 if 语句才能完成这项工作?

标签: phpwordpresswoocommerce

解决方案


您可以使用以下功能:wc_get_customer_order_count()

https://docs.woocommerce.com/wc-apidocs/function-wc_get_customer_order_count.html

function mbm_redirect_depending_on_product_id() {
    if (!is_wc_endpoint_url('order-received') || empty($_GET['key'])) {
        return;
    }

    $order_id = wc_get_order_id_by_order_key($_GET['key']);
    $order = wc_get_order($order_id);

    // Getting the user ID
    $user_id = $order->get_user_id();

    // Get the user order count
    $order_count = wc_get_customer_order_count( $user_id );

    if ( $order_count == 2 ) {
        wp_redirect('/thankyou');
        exit;
    } else {
        wp_redirect('/thankyou-2');
        exit;
    }
}
add_action('template_redirect', 'mbm_redirect_depending_on_product_id');

推荐阅读