从Woocommerce中购买的产品ID中获取最后的订单ID

问题描述 投票:1回答:2

如果客户购买了产品,如何获得特定产品的订单ID?我尝试了以下代码,但没有奏效。我在这里先向您的帮助表示感谢。

<?php
 $order = new wc_get_order( $order_id );
 $order->get_id();
 echo $order->get_order_number();
?>

尝试了这个代码,但没有奏效。

$product_ids = array(37,53);
$order_ids = get_order_ids_from_bought_items( $product_ids );
php wordpress woocommerce product orders
2个回答
1
投票
function get_order_ids_from_bought_items() {

    $prod_arr = array('37', '53');
    $purchased = false;

    $customer_orders = get_posts(array(
        'numberposts' => -1,
        'post_type' => 'shop_order',
        'meta_key' => '_customer_user',
        'meta_value' => get_current_user_id(),
            ));
    foreach ($customer_orders as $order_post) {


        $order = wc_get_order($order_post->ID);

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

            $product_id = $item->get_product_id();

            if (in_array($product_id, $prod_arr))
                $purchased = true;
        }
    }

    return $purchased; // $order_post->ID  for Order ID
}

1
投票

以下函数使用非常轻量级的SQL查询,该查询将从给定客户的已定义产品ID返回最后一个订单ID:

function get_last_order_id_from_product( $product_id, $user_id = 0 ) {
    global $wpdb;

    $customer_id = $user_id == 0 ? get_current_user_id() : $user_id;

    return $wpdb->get_var( "
        SELECT p.ID FROM {$wpdb->prefix}posts AS p
        INNER JOIN {$wpdb->prefix}postmeta AS pm ON p.ID = pm.post_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_items AS woi ON p.ID = woi.order_id
        INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS woim ON woi.order_item_id = woim.order_item_id
        WHERE p.post_type = 'shop_order'
        AND pm.meta_key = '_customer_user'
        AND pm.meta_value = $customer_id
        AND woim.meta_key IN ( '_product_id', '_variation_id' )
        AND woim.meta_value = $product_id
        ORDER BY p.ID DESC  LIMIT 1
    " );
}

代码在您的活动子主题(或活动主题)的function.php文件中。经过测试和工作。

如果客户尚未购买产品,则该功能将返回false

用法示例:

在下面,您将设置产品ID 37和可选用户ID 153(如果您不使用前端代码,其中函数可以获取当前用户ID)* /

$order_id = get_last_order_id_from_product( 37, 153 );

或者对于当前用户:

$order_id = get_last_order_id_from_product( 37 );
© www.soinside.com 2019 - 2024. All rights reserved.