shashank
shashank

Reputation: 566

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?

Upvotes: 2

Views: 13136

Answers (4)

mohamed jalloun
mohamed jalloun

Reputation: 11

try to use WP_Query

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

    $query = new WP_Query($args);

    foreach ($query as $key) {

        $last_soto_property = $key->ID;
    }
var_dump($last_soto_property);

this will show the ID of your last custom post type.

Upvotes: 1

shashank
shashank

Reputation: 566

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];

Upvotes: 0

sirBlond
sirBlond

Reputation: 335

you can use wp_get_recent_posts function. Here's a sample function:

$args = array(
    'post_type' =>'soto_property',
    'posts_per_page' => 1
);
$recent_post = wp_get_recent_posts($args, OBJECT);

Check function reference page in codex for more information.

Upvotes: 3

MMK
MMK

Reputation: 605

Your PHP code contains one small mistake:

posts_per_page is set to 1. it should be higher than one. This is why you are getting only one result out of the results that were queried.

So instead of 'posts_per_page' => 1 you could use 'posts_per_page' => your_desired_number_of_post_here

Your complete code should look like:

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

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

Upvotes: -1

Related Questions