从所有WooCommerce预订中获取所有人员的总和

时间:2020-11-03 11:33:19

标签: php wordpress woocommerce count woocommerce-bookings

我使用了官方的woocommerce预订插件,并且尝试获取所有已预订产品的人数。

对于没有问题的单个订单:

if ( is_callable( 'WC_booking_Data_Store::get_booking_ids_from_order_id') ) {
        $booking_data = new WC_booking_Data_Store();
        $booking_ids = $booking_data->get_booking_ids_from_order_id( $order->get_id() );
    }
            foreach ( $booking_ids as $booking_id ) {
            $booking = new WC_booking( $booking_id );
            
            $person_count = array_sum( $booking->get_person_counts() );
            $total_person_count .= 'Booking id: ' . $booking_id . ' Person Count: ' . $person_count . ' ';
        }

但是如何收集所有预订的总和?希望你能帮助我

2 个答案:

答案 0 :(得分:1)

要获得所有“完整”的预订人数,请使用以下内容:

// get all bookings Ids with a status "complete"
$bookings_ids = get_posts( array(
    'posts_per_page' => -1,
    'post_type'      => 'wc_booking', // booking post type
    'post_status'    => 'complete',
    'fields'         => 'ids',
));

$persons_count = 0; // Initializing
$persons_html  = '<table><tr><th>Booking id</th><th>Persons count</th></tr>'; // Initializing

// Loop through booking Ids
foreach ( $bookings_ids as $booking_id ) {
    $booking = new WC_Booking( $booking_id ); // Get the WC_Booking instance object
    $count   = array_sum( $booking->get_person_counts() );

    $persons_count += $count;
    $persons_html  .= '<tr><td>' . $booking_id . '</td><td>' . $count . '</td></tr>';
}
$persons_html .= '<tr><th><strong>Total count</th><td style="color:red">' . $persons_count . '</td></tr>';

// Output
echo $persons_html . '</table>';

经过测试可以正常工作。

要减轻重量,您可以更换:

    $booking = new WC_Booking( $booking_id ); // Get the WC_Booking instance object
    $count   = array_sum( $booking->get_person_counts() );

简单地:

    $count   = array_sum( get_post_meta($booking_id, '_booking_persons', true) );

答案 1 :(得分:0)

按照您更新的代码,请尝试此

<?php
if ( is_callable( 'WC_booking_Data_Store::get_booking_ids_from_order_id') ) {
    $booking_data = new WC_booking_Data_Store();
    $booking_ids = $booking_data->get_booking_ids_from_order_id( $order->get_id() );
}
$total_count_data = array();
$total_count_persons = 0;
foreach ( $booking_ids as $booking_id ) {
    $booking = new WC_booking( $booking_id );
    $person_count = array_sum( $booking->get_person_counts() );
    $total_count_persons+= $person_count;
    $total_count_data[] = array(
            'Booking'   => $booking_id,
            'Person'    => $person_count
        );
}