1

I'm trying to build a wp_query for two post types (post and product. The second is a woocommerce custom post type). The goal is to get a list of posts sorted by date. Something like this:

 - Post 3.    (april, 3)
 - Post 2.    (march, 15)
 - Product 2. (february, 10)
 - Post 1.    (january, 4)
 - Product 1. (january, 1)

I have this arguments:

$args = array (
  'post_type'         => array( 'product', 'post' ),
  'nopaging'          => true,
  'meta_key'          => '_featured',
  'meta_value'        => 'yes',
  'orderby'           => 'date',
  'order'             => 'desc',
);

But it returns a separated lists of post types:

 - Post 3.    (april, 3)
 - Post 2.    (march, 15)
 - Post 1.    (january, 4)

 - Product 2. (february, 10)
 - Product 1. (january, 1)

How can I get a unique list mixing the two post types? (as in the first example) Thank you in advance.

  • Your query looks fine to me. Have you tried to print_r( $query->request ); after creating your new WP_Query object? That should give you the raw SQL. – kovshenin Aug 1 '16 at 19:07
  • It returs this: SELECT wp_posts.* FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) WHERE 1=1 AND ( ( wp_postmeta.meta_key = '_featured' AND CAST(wp_postmeta.meta_value AS CHAR) = 'yes' ) ) AND wp_posts.post_type IN ('product', 'post') AND (wp_posts.post_status = 'publish') GROUP BY wp_posts.ID ORDER BY wp_posts.post_date DESC – aitor Aug 2 '16 at 7:03
  • That looks fine. Could you check the post_date fields directly in your database? Maybe the products were published a few years ago :) – kovshenin Aug 2 '16 at 7:29
  • Thank you for the answer! This WP is in local development, with new entries that I can delete or add to try it. I think this is a normal behavior for this query: to list post ordered by date and, then, to list products ordered by date. In order to be completely clear, I ask for a method to get a unique list ordered by date, regardless of the post type (maybe with wp_query arguments or maybe rearranging this wp_query results). – aitor Aug 2 '16 at 8:27
  • Given your query, it should do exactly what you are asking. Unless you or some plugin is doing something strange and rearranging the results manually via some WP_Query filter, then my guess is that the dates in the database are incorrect. Try and run the query directly in MySQL and see what order you get. – kovshenin Aug 2 '16 at 8:41
0

Finally, the problem seems to be that posts was marked as sticky, not featured, and prepend other posts. So, I have featured products and sticky posts. I need to add featured meta key to posts and remove sticky flag.

Thank you very much Kovshenin

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.