Getting the last post id does not work as expected

I am trying to get the latest post id in WordPress, but the two different methods I am using return different results.

FYI, if I look in PHPmyAdmin I see that the last 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 strange.

But if I list some message 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 well supported.

I understand that "post_type" => "any" should include all post types, and obviously I don't want to use the second method because I will have to update the array manually every time a new post type appears.

Is there a way to get around this? Or maybe a better way to get the latest post id?

+3


source to share


2 answers


Use this code 100% working and tested:

Note. When registering a new post type, the below conditions are automatically added.



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;

      

0


source


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.

0


source







All Articles