我进行了自定义wp_query,以在woocommerce主页上显示我的销售产品,但是我无法在主页上显示正确的销售产品。我只能看到3种产品(其中有2种没有销售)。 Shordcode显示正确的销售产品,但我的查询变得疯狂。我不能使用简码,因为我需要创建轮播。
以下代码:
$args = array(
'post_type' => 'product',
'posts_per_page' => -1,
'meta_query' => array(
'relation' => 'OR',
array( // Simple products type
'key' => '_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
),
array( // Variable products type
'key' => '_min_variation_sale_price',
'value' => 0,
'compare' => '>',
'type' => 'numeric'
)
)
);
$saleproducts = new WP_Query( $args );
if ( $saleproducts->have_posts() ) :
while ( $saleproducts->have_posts() ) : $saleproducts->the_post();
$post_thumbnail_id = get_post_thumbnail_id();
$product_thumbnail = wp_get_attachment_image_src($post_thumbnail_id, $size = 'shop-feature');
$product_thumbnail_alt = get_post_meta( $post_thumbnail_id, '_wp_attachment_image_alt', true );
----MY HTML CODE HERE----
endwhile; endif;
wp_reset_query();
wp_reset_postdata();
答案 0 :(得分:0)
我已经测试了您的代码,由于_min_variation_sale_price
表中不存在postmeta
,因此它不适用于变体产品。所以我有更改查询以获取特价产品。如下:
$query_args = array(
'posts_per_page' => -1,
'no_found_rows' => 1,
'post_status' => 'publish',
'post_type' => 'product',
'meta_query' => WC()->query->get_meta_query(),
'post__in' => array_merge(array(0), wc_get_product_ids_on_sale())
);
$products = new WP_Query($query_args);
if ($products->have_posts()) :
while ($products->have_posts()) : $products->the_post();
$post_thumbnail_id = get_post_thumbnail_id();
$product_thumbnail = wp_get_attachment_image_src($post_thumbnail_id, $size = 'shop-feature');
$product_thumbnail_alt = get_post_meta($post_thumbnail_id, '_wp_attachment_image_alt', true);
echo get_the_title() . ' - ' . get_the_ID() . '<br/>';
// ----MY HTML CODE HERE----
endwhile;
endif;
使用此代码,您可以获得所有特价产品。我已经从here中引用了它。
希望这对您有所帮助。