1

I have this code

<?php
$dateTimeStart = new DateTime(tribe_get_start_date( null, false, 'Y-m-d' ));
$dateTimeEnd   = new DateTime(tribe_get_start_date( null, false, 'Y-m-d' ));
$bookings = WC_Bookings_Controller::get_bookings_in_date_range(
        $dateTimeStart->getTimestamp(),
        $dateTimeEnd->getTimestamp(),
        '',
        false
      );

$booked[] = 0;
foreach ($bookings as $booking) {
$booked[] = $booking->product_id;
}

$args = array (
  'post__in' => $booked,
  'post_type' => ['product'],
);

$query = new WP_Query( $args );
$posts = $query->posts;
$sku = $product->get_sku();
wp_reset_query();
?>

What is the right way to extract SKU from the above query?

I tried

<?php echo esc_html( get_post_meta( get_the_ID(), '_sku', true ) ); ?>

which working for this query

<?php
$args = array( 'post_type' => 'product', 'terms' => array('fvip-ddb','fvip-sdb'), 'posts_per_page' => -1, 'meta_key' => '_regular_price' );
$loop = new WP_Query( $args );
$sku = get_post_meta( $item['product_id'], '_sku', true );
?>

but not working (showing blank) for the first query

UPDATE

using code from below, when I run this:

<?php foreach($posts as $post) { echo "{ toolTip: \"Say something here.\", key : \"$skubooked\", staticState: true },"; } ?>

for some reason the loop return the same value 3 times. (There are three different product bookings .. but the loop showing the same product three times) ..

Work
  • 41
  • 1
  • 7
  • if the loop return a product 3 times, This come from your argument `$booked` (for `post__in` in the `WP_Query`… You should try to `print_r($booked)` before the `WP_Query` to see what you get. – LoicTheAztec Jun 28 '18 at 19:06

1 Answers1

1

There is multiple ways to get the product SKU:

  1. Using WordPress get_post_meta() with the meta key _sku
  2. Using The WC_Product method get_sku() on the WC_product object

Your query should like in the following code:

$query = new WP_Query( array(
    'post_type'      => 'product',
    // 'post_status'    => 'publish',
    'posts_per_page' => -1 ,
    'post__in'       => $booked,
) );

if ( $query->have_posts() ): while ( $query->have_posts() ): $query->the_post();

    $sku = get_post_meta( get_the_ID(), '_sku', true );

endwhile; wp_reset_query(); endif;

Or

$query = new WP_Query( array(
    'post_type'      => 'product',
    // 'post_status'    => 'publish',
    'posts_per_page' => -1 ,
    'post__in'       => $booked,
) );

if ( $query->have_posts() ): while ( $query->have_posts() ): $query->the_post();

    // get an instance of the WC_product object
    $product = wc_get_product( get_the_ID() );

    $sku = $product get_sku();

endwhile; wp_reset_query(); endif;
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
  • 1
    sorry my bad .. error in my code .. thank you very much for the help .. really appreaciate it!! – Work Jun 28 '18 at 19:17