My WP_Query request looks like:

$query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product' );
$query_args['meta_query'] = $woocommerce->query->get_meta_query();
$query_args['meta_query'][] = array(
    'key' => '_featured',
    'value' => 'yes'
);

$r = new WP_Query($query_args);

What argument I need to add to return a query ordered by IDs in a particular row (ex. I need to return products IDs 161,165,131,202 in that order).

Edit: I have added a post__in and orderby arguments which pulls only those particular products by IDs but not in the order specified in the array but it looks like based on when product was added to the back end.

$query_args = array('posts_per_page' => $products, 'no_found_rows' => 1, 'post_status' => 'publish', 'post_type' => 'product', 'post__in' => array(161,165,131,202), 'orderby' => 'post__in', 'order' => 'ASC' );

WP Query for that looks like:

SELECT wp_posts.ID 
FROM wp_posts  
INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id )  
INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) 
WHERE 1=1  
AND wp_posts.ID IN (161,165,131,202) 
AND wp_posts.post_type="product" 
AND ((wp_posts.post_status="publish")) 
AND ( ( wp_postmeta.meta_key = '_visibility' 
AND CAST(wp_postmeta.meta_value AS CHAR) IN ('visible','catalog') ) 
AND (mt1.meta_key = '_featured' AND CAST(mt1.meta_value AS CHAR) = 'yes' )) 
GROUP BY wp_posts.ID 
ORDER BY wp_posts.menu_order, FIELD( wp_posts.ID, 161,165,131,202 ) 
LIMIT 0, 5

no clue why ORDER BY is set to be menu_order not post__in

3 Answers
3

To keep the same post order as it was passed to the post__in parameter, you need to pass post__in as value to orderby argument and ASC to the order argument

$query_args = [
    'posts_per_page' => $products, 
    'no_found_rows'  => true, 
    'post_type'      => 'product', 
    'post__in'       => [161,165,131,202],
    'orderby'        => 'post__in',
    'order'          => 'ASC'
];

EDIT

Looking at your edit, you have a bad filter somewhere, most probably a bad pre_get_posts action or a posts_orderby filter. Do the two following tests

  • Add 'suppress_filters' => true, to your query arguments, if that helps, you have a bad filter

  • Add remove_all_actions( 'pre_get_posts' ); before you do your query, if that helps, you have a bad pre_get_posts filter

  • A third, but most probable useless check would be to add wp_reset_query() before the custom query, if that helps, you have a bad query somewhere, most probably one using query_posts

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *