I've trying to get the latest post ID in WordPress, but the two different methods I am using are returning different results.
FYI if I look in PHPmyAdmin I can see the latest post ID is 3000.
If I do this...
$args = array(
'post_type' => 'any'
);
$the_ID = get_posts($args);
$latest_ID = $the_ID[0]->ID;
echo $latest_ID;
...it returns 2999 instead of 3000. This is very odd.
But if I specify some post types in an array like this...
$args = array(
'post_type' => array('post', 'page', 'attachment')
);
$the_ID = get_posts($args);
$latest_ID = $the_ID[0]->ID;
echo $latest_ID;
...it returns 3000 which is the correct ID but also not very maintainable.
My understanding is that 'post_type' => 'any' should include all post types, and obviously I don't want to use the 2nd method because I'd have to update the array manually every time there is a new post type.
Is there a way around this? Or perhaps a better way of getting the latest post ID?
Use this code 100% working and tested:
Note: When you register new post type then automatically will be add in below conditions.
function get_all_custom_post_types() {
$args = array( 'public' => true );
$output = 'objects'; //'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$custom_post_types = get_post_types( $args, $output, $operator );
$post_types = array();
foreach ( $custom_post_types as $k => $post_type ) {
$post_types[] = $post_type->name;
}
return $post_types;
}
//print_r(get_all_custom_post_types()); // Array ( [0] => post [1] => page [2] => attachment [3] => product [4] => movies )
$args = array(
'post_type' => get_all_custom_post_types(),
'posts_per_page' => 10
);
$latest_cpt = get_posts($args );
//print_r($latest_cpt);
echo $latest_cpt[0]->ID;
I found the problem...
The post type of one of my plugins was not public. I changed it from false to true...
'public' => true
...and now if I use 'post_type' => 'any' it works fine.