[英]Woocommerce - Show products on sale on wordpress homepage - wp_query
我制作了自定義 wp_query 以在 woocommerce 主頁上顯示我的銷售產品,但我無法在主頁上顯示正確的銷售產品。 我只能看到 3 個產品(其中一個在打折,另外兩個沒有)。 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();
我已經測試了您的代碼,它不適用於變體產品,因為postmeta
表中不存在_min_variation_sale_price
。 所以我有更改查詢以獲取銷售產品。 如下:
$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;
使用此代碼,您可以獲得所有特價商品。 我從這里參考了它。
希望這對你有幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.