Zubi Cloud hướng dẫn cách Hiển thị các sản phẩm đã mua ở trang Account trong WooCommerce. Khi khách hàng WooCommerce đã đăng nhập, bạn có thể muốn hiển thị danh sách các sản phẩm đã mua, ví dụ: trong tab “Tài khoản của tôi” tùy chỉnh .
Tôi đã quyết định viết mã này dưới dạng shortcode để bạn có thể sử dụng đoạn mã này ở bất kỳ đâu trong các mẫu WooCommerce của mình, miễn là người dùng đã đăng nhập và miễn là nó có đơn đặt hàng đang xử lý hoặc hoàn thành.
![Hiển thị các sản phẩm đã mua ở trang Account trong WooCommerce 1 Hiển thị các sản phẩm đã mua ở trang Account trong WooCommerce](https://help.zubi.cloud/wp-content/uploads/2021/10/woocommerce-show-list-produ.jpg)
Các bước cài đặt Hiển thị tất cả các sản phẩm được người dùng mua trong WooCommerce như sau:
Bước 1: Truy cập vào woocommerce/myaccount. mở file dashboard.php và chèn đoạn code sau vào nơi cần hiển thị các sản phẩm đã mua
<div class='zubicloud-acc-purchased-products'> <h3>Sản phẩm đã mua</h3> <?php echo do_shortcode('[my_purchased_products]'); ?> </div>
Hoặc bạn có thể sử dụng shortcode để chèn vào nơi khác:
[my_purchased_products]
Bước 2: Chèn đoạn code sau vào file functions.php để Hiển thị các sản phẩm đã mua ở trang Account trong WooCommerce
/** Hiển thị tất cả các sản phẩm được người dùng mua **/ add_shortcode( 'my_purchased_products', 'bbloomer_products_bought_by_curr_user' ); function bbloomer_products_bought_by_curr_user() { // GET CURR USER $current_user = wp_get_current_user(); if ( 0 == $current_user->ID ) return; // GET USER ORDERS (COMPLETED + PROCESSING) $customer_orders = get_posts( array( 'numberposts' => -1, 'meta_key' => '_customer_user', 'meta_value' => $current_user->ID, 'post_type' => wc_get_order_types(), 'post_status' => array_keys( wc_get_is_paid_statuses() ), ) ); // LOOP THROUGH ORDERS AND GET PRODUCT IDS if ( ! $customer_orders ) return; $product_ids = array(); foreach ( $customer_orders as $customer_order ) { $order = wc_get_order( $customer_order->ID ); $items = $order->get_items(); foreach ( $items as $item ) { $product_id = $item->get_product_id(); $product_ids[] = $product_id; } } $product_ids = array_unique( $product_ids ); $product_ids_str = implode( ",", $product_ids ); // PASS PRODUCT IDS TO PRODUCTS SHORTCODE return do_shortcode("[products ids='$product_ids_str']"); }