Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of a post by id in wordpress

Tags:

php

wordpress

I have an id:

$id = 151;

I want to check existence like this:

$content = get_post($id);
if ($content)
    echo "post $id already exists";
else
    echo "post $id does not exists or was deleted";

But in the WP forums always seems prefer ask to DB:

global $wpdb;
$post_exists = $wpdb->get_row("SELECT * FROM $wpdb->posts WHERE id = '" . $id . "'", 'ARRAY_A');
if ($post_exists)
    echo "post $id exists";
else
    echo "post $id does not exist";

So which is the best method? Indeed I prefer the ease of the first one.

like image 697
Igor Parra Avatar asked Mar 09 '12 17:03

Igor Parra


1 Answers

if( is_null(get_post($id))){

      echo "post $id does not exists or was deleted";

}else{

       echo "post $id already exists";

}
like image 126
Dnyanesh Avatar answered Nov 15 '22 16:11

Dnyanesh