【发布时间】:2018-12-21 05:12:28
【问题描述】:
您好,我正在同时学习 PHP 和 Woocommerce! 我正在尝试获取所有具有状态处理的订单以及每个订单的总数并将其显示在页面上。
到目前为止,我可以遍历所有订单并获取每个订单的名称和数量。
但由于我不知道列表中将包含哪种产品,我不确定如何比较名称然后添加数量。
我目前的输出是这样的:
prod1 - v1 x 1
Prod2 - v3 x 1
prod2 - v3 x 1
prod3 - v2 x 11
prod3 - v2 x 1
我想要的是:
prod1 - v1 x 1
Prod2 - v3 x 2
prod3 - v2 x 12
目前的代码是:
<?php
/*
Template Name: Print Supplier Order
*/
if (!is_user_logged_in() || !current_user_can('manage_options')) wp_die('This page is private.');
?>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title><?php _e('Processing Orders'); ?></title>
<style>
body { background:white; color:black; width: 95%; margin: 0 auto; }
</style>
</head>
<body>
<header>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1 class="title"><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile; endif; ?>
</header>
<section>
<?php
global $woocommerce;
$args = array( 'post_type' => 'shop_order', 'post_status' => 'wc-processing', 'posts_per_page' => -1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
$order = new WC_Order($order_id);
$product_details = array();
$order_items = $order->get_items();
foreach( $order_items as $product ) {
echo $product['name']." x ".$product['qty'];
echo '<br>';
}
?>
<?php endwhile; ?>
</section>
</body>
</html>
【问题讨论】:
-
$order->get_items()返回什么?你能改变这个吗? -
它返回当前订单循环的产品数组。我不知道是否有更好的方法来获取这些信息。
-
虽然可能有更好的方法,但一种解决方案是遍历数组,创建一个新数组,如下所示:
$order_items = array(); foreach ($order->get_items() as $product) { $order_items[$product['name']] += $product['qty']; } foreach ($order_items as $product => $qty) { echo "$product x $qty <br />"; }
标签: php sql wordpress woocommerce orders