繁体   English   中英

从 WooCommerce 中的最后订单中获取产品

[英]Get products from last orders in WooCommerce

我想显示用户过去订购的最后 10 种产品。

问题是,我不知道最后一个订单中有多少产品。 所以我可能需要获得不止一份订单。

我想显示购物车中的所有内容。 让用户再次购买产品。 稍后我想排除当前购物车中的产品。

对于最后一个订单,我在这里找到了一个片段: https ://stackoverflow.com/a/71501798/1788961

// For logged in users only
if ( is_user_logged_in() ) {

    // The current user ID
    $user_id = get_current_user_id();

    // Get the last WC_Order Object instance from current customer
    $last_order = wc_get_customer_last_order( $user_id );

    // NOT empty
    if ( ! empty( $last_order ) ) {
        // Initalize
        $product_ids = array();

        // Loop
        foreach ( $last_order->get_items() as $item ) {
            // Get product ID
            $product_id = $item->get_product_id();
            $product_ids[] = $product_id;
        }

        echo '<pre>';
        var_dump( $product_ids );
        echo '</pre>';
    }
}

有没有办法将功能扩展到更多订单?

您确实可以使用wc_get_orders() ,您将在其中根据参数检索订单,例如用户 ID 和按日期排序。

另请注意,使用的限制为 10。 这是因为我们可以假设每个订单至少包含 1 件产品。 因此,如果您想收集 10 个产品,则限制永远不会超过 10 个订单:

// Args
$args = array(
    'customer_id'   => get_current_user_id(),
    'limit'         => 10,
    'orderby'       => 'date',
    'order'         => 'DESC',
    'status'        => array( 'wc-on-hold','wc-processing','wc-completed' ),
);

// Get orders
$orders = wc_get_orders( $args );

// NOT empty
if ( ! empty ( $orders ) ) {
    // Initalize
    $product_ids = array();

    foreach ( $orders as $order ) {
        // Loop through order items
        foreach ( $order->get_items() as $item ) {
            // Get product ID
            $product_id = $item->get_product_id();

            // Limit of 10 products
            if ( count( $product_ids ) < 10 ) {
                // Push to array
                $product_ids[] = $product_id;
            } else {
                break;
            }
        }
    }

    // The output
    echo '<pre>', print_r( $product_ids, 1 ), '</pre>';
}

一个更轻、更快的解决方案是使用自定义 SQL 查询:

global $wpdb;

$current_user = wp_get_current_user();
$customer_email = $current_user->user_email;

$result = $wpdb->get_col( "
    SELECT oim.meta_value 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 oi ON p.ID = oi.order_id
    INNER JOIN {$wpdb->prefix}woocommerce_order_itemmeta AS oim ON oi.order_item_id = oim.order_item_id
    WHERE p.post_status IN ( 'wc-on-hold','wc-processing','wc-completed' )
    AND pm.meta_key = '_billing_email'
    AND pm.meta_value = '$customer_email'
    AND oim.meta_key = '_product_id'
    AND oim.meta_value != 0
    ORDER BY p.post_date DESC LIMIT 0, 10
" );

// The raw output
echo '<pre>', print_r( $result, 1 ), '</pre>';

无论您喜欢哪个选项。 在任何情况下,这些都可以通过变量、可变产品或基于多个订单状态进行扩展。 排除重复产品等。所以这取决于您的需求

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM