【问题标题】:Get sku from Woocommerce product bookings in a WP_Query在 WP_Query 中从 Woocommerce 产品预订中获取 sku
【发布时间】:2018-06-28 17:27:35
【问题描述】:

我有这个代码

<?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();
?>

从上述查询中提取 SKU 的正确方法是什么?

我试过了

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

适用于这个查询

<?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 );
?>

但对于第一个查询无效(显示空白)

更新

使用下面的代码,当我运行它时:

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

由于某种原因,循环返回相同的值 3 次。 (有三种不同的产品预订.. 但循环显示相同的产品三次)..

【问题讨论】:

  • 如果循环返回一个产品 3 次,这来自你的论点 $booked(对于 post__in 中的 WP_Query... 你应该尝试在 print_r($booked) 之前查看 WP_Query你得到什么。

标签: php wordpress woocommerce woocommerce-bookings sku


【解决方案1】:

获取产品SKU的方式有多种:

  1. 使用 WordPress get_post_meta() 和元键 _sku
  2. WC_product 对象上使用WC_Product 方法get_sku()

您的查询应与以下代码类似:

$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;

或者

$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;

【讨论】:

  • 对不起我的错误..我的代码有错误..非常感谢您的帮助..真的很感激!!
猜你喜欢
  • 2018-02-25
  • 1970-01-01
  • 2018-11-19
  • 2023-03-14
  • 2017-02-21
  • 2017-11-01
  • 2014-07-04
相关资源
最近更新 更多