Check existence of a post by id in wordpress

I think the best is to query the database directly as less as possible

You can use the get_post_status() function.

It returns false if the post doesn't exist

if ( get_post_status( $post_id ) ) {
    // do stuff
}

or, to be sure that the post is published

if ( 'publish' === get_post_status( $post_id ) ) {
    // do stuff
}

https://developer.wordpress.org/reference/functions/get_post_status/


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

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

}else{

       echo "post $id already exists";

}

Tags:

Php

Wordpress