Search code examples
wordpresspostcustom-post-type

How to get Last post Id of custom post type in wordpress


I want to get the last post id of a custom post type in WordPress. For this, I tried this code-

$args = array(
    'post_type' =>'soto_property',
    'posts_per_page' => 1,
    'orderby'=>'post_date',
    'order' => 'DESC',
);

$image_posts = get_posts($args);
foreach ( $image_posts  as $post ) {
    echo $post->ID;
}

But It always returns me the First post id of this custom post type. I have tried 'order'=>'ASC' also but it gives me the same result.

How can I achieve the last post id of this CPT?


Solution

  • I have got my last inserted Post id using $wpdb query as below-

    global $wpdb;
    $lastrowId=$wpdb->get_col( "SELECT ID FROM wp_posts where post_type='soto_property' ORDER BY post_date DESC " );
    
    $lastPropertyId=$lastrowId[0];