Check for message by id in wordpress

I have an id:

$id = 151;


I want to check for existence like this:

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


But on the WP forums it always seems that they prefer to access the DB:

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


So which is the best method? Indeed, I prefer the lightness of the former.


source to share

5 answers

I think that if they give you a function to call, you call it; use a database for things that are not provided by the function.



I think it is best to query the database as little as possible

You can use get_post_status () function.

It returns false if the message doesn't exist

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


or to be sure that the publication is published

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



I find it very irresponsible not to consider the efficiency of calls when handling them on the server. Generic C / C ++ implementations are usually not optimized for everyone and call scalability needs to be considered. There is a balance between optimization and maintainability, but to make an open statement that the PHP world shouldn't care about resource usage is naive and ultimately lazy. You can take your case to the extreme and build a php programmer team to get rid of the unnecessary code and make sure the core OS libraries are going to make things work at their best ...



I know this is a very old post, but still ... If you want to check if a post with a specific ID exists, you can also use the wordpress get_permalink function.


if( get_permalink( $post_id ) ):
echo "does exist";
echo "does not exist";


Note that the get_permalink function also returns pages, attachment links, and more.



I'd rather query the database by calling get_post.

The message content can be large. Querying and pushing the entire content of a message into a string to check if it exists is incredibly wasteful and inefficient.

If you don't want to access the database directly, perhaps using get_post_field to pull one of the smaller fields would be just as efficient, but less wasteful.



All Articles