朋友们,我们真的需要你们的帮助。问题是如何在商品档案中的卡片上显示购买的商品数量?试过这样
function custom_quantity_field_archive() {
$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()),
));
foreach ($customer_orders as $customer_order) {
$order = wc_get_order($customer_order->ID);
$items = $order->get_items();
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
global $product;
$qty = $item->get_quantity();
if ($refunded_qty) {
$qty_display = '<del>' . esc_html($qty) . '</del> <ins>' . esc_html($qty - ( $refunded_qty * -1 )) . '</ins>';
} else {
$qty_display = esc_html($qty);
}
} echo 'Available: ' . $qty_display . ' ';
}
}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 9 );
但每张卡片都会显示每件购买商品的数量,而不仅仅是其中一件。
答案 0 :(得分:1)
我修改了你的代码。您需要比较 product
中的 loop
和您从客户订单中获得的 product
。
function custom_quantity_field_archive() {
global $product;
$id = $product->get_id();
$link = $product->get_permalink();
$customer_orders = get_posts(array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => get_current_user_id(),
'post_type' => wc_get_order_types(),
'post_status' => array_keys(wc_get_is_paid_statuses()),
));
$qty = 0;
foreach ($customer_orders as $customer_order) {
$order = wc_get_order($customer_order->ID);
$items = $order->get_items();
foreach ($order->get_items() as $item_id => $item) {
$product_id = $item->get_product_id();
if( $id == $product_id ){
$qty = $qty + $item->get_quantity();
}
}
}
echo 'Purchased: ' . $qty . ' ';
}
add_action( 'woocommerce_after_shop_loop_item', 'custom_quantity_field_archive', 9 );