0

I have two post types Type_1 and Type_2

I'm trying to get the most recent out of both of them so if type_1 has a post created after the most recent of type_2 then I want to show that post and the other way around.

What is the best way of doing this?

I only want to show 1 post the most recent out of both

1

Just set post_type to an array of types, and posts_per_page to 1 and you'll get the most recent post from those types.

$args = array(
    'post_type' => array( 'type_1', 'type_2' ),
    'posts_per_page' => 1
);
$latest = new WP_Query( $args );
4
  • See this is what I had thought as well but it doesn't seem to work it just gets the fist from the first post type even if i make a new post in the other Nov 7 '16 at 4:04
  • Make sure you don't have some code elsewhere in the theme or a plugin altering the query, like an incorrectly targeted pre_get_posts filter or something. If you var_dump($latest) after you run the query, you'll see the query vars and resultant SQL that was sent to the database. I've tested it here with latest WP and the 2016 theme and it works as expected.
    – Milo
    Nov 7 '16 at 4:42
  • @Milo Can't we use wp_get_recent_posts() to do that ?
    – Ranuka
    Nov 7 '16 at 5:07
  • 1
    @Ranuka - You could use that if you wanted to, it creates a new WP_Query object via get_posts, so arguments are the same either way.
    – Milo
    Nov 7 '16 at 5:27
0

This is the way that ended up working for me thanks for all your help

$type_1 = get_posts(array(
   'post_type' => 'type_1',
   'posts_per_page' => 1,
   'orderby' => 'date',
   'order' => 'DESC'
));

   $type_1_query_obj = $type_1[0];
   $type_1_date = $type_1_query_obj->post_date;
   $type_1_name = $type_1_query_obj->post_title;



$type_2 = get_posts(array(
   'post_type' => 'type_2',
   'posts_per_page' => 1,
   'orderby' => 'date',
   'order' => 'DESC'
));

   $type_2_query_obj = $type_2[0];
   $type_2_date = $type_2_query_obj->post_date;
   $type_2_name = $type_2_query_obj->post_title;


//compare the dates

if( strtotime($type_1_date) > strtotime($type_2_date) ) {
   echo $type_1_name;
}else{
   echo $type_2_name;
}

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.