如何通过查询获取指定ID的WooCommerce产品并按ID顺序展示?
问题:产品未按传入的ID顺序展示
在使用WP_Query查询产品时,即便通过post__in指定了ID列表,WordPress默认会以发布日期排序,而非传入的ID顺序。要让产品严格按照给定ID数组的顺序展示,需手动指定查询的排序规则。
解决方案
在查询参数$args中添加'orderby' => 'post__in',强制查询按照post__in中ID的先后顺序返回结果(order默认值为ASC,可省略,明确写出更清晰)。
修改后的完整代码
function displayProducts($product_ids) { $args = array( 'post_type' => 'product', 'post__in' => $product_ids, 'posts_per_page' => count($product_ids), // 指定排序规则,匹配传入的ID顺序 'orderby' => 'post__in', 'order' => 'ASC' ); $products_query = new WP_Query($args); if ($products_query->have_posts()) { while ($products_query->have_posts()) { $products_query->the_post(); $product = wc_get_product(); $product_id = get_the_ID(); $product_title = get_the_title(); $image_id = get_post_thumbnail_id($product_id); $image_url = wp_get_attachment_image_url($image_id, 'full'); $categories = get_the_terms($product_id, 'product_cat'); $artists = wc_get_product_terms($product_id, 'artiste'); $parts = explode(' – ', $product_title, 2); $title = isset($parts[0]) ? $parts[0] : ''; echo ' <div class="item"> <div class="content"> <a href="' . get_permalink($product_id) . '"> <img src="' . esc_url($image_url) . '" alt="' . $product_id . '" /> </a> <div class="text"> <a href="' . get_permalink($product_id) . '"> <h3>' . esc_html($title) . $product_id . '</h3> </a>'; if ($artists && !empty($artists)) { $artist = $artists[0]; echo '<p>par <a href="' . get_term_link($artist) . '">' . esc_html($artist->name) . '</a></p>'; } if ($categories && !is_wp_error($categories)) { $category_links = array(); echo '<div class="categories">'; foreach ($categories as $category) { $category_links[] = '<a class="category" href="' . get_term_link($category) . '">' . $category->name . '</a>'; } echo implode(', ', $category_links); echo '</div>'; } echo ' </div> </div> </div>'; } wp_reset_postdata(); } }
补充说明
添加'orderby' => 'post__in'后,WP_Query会完全遵循$product_ids数组的顺序返回产品,不管你是随机生成还是按其他规则生成的ID列表,都能精准匹配排序。
内容的提问来源于stack exchange,提问作者Kidoly
相关产品推荐
相关产品推荐

