How to Check if a Post Exists in WordPress? (+Example)

WordPress has many ways to check a post's existence by ID, title, content, date, and ETC. get_post and post_exists are two useful functions in WordPress collection that can help developers check the existence of any post. Let review these two functions and try their usage.

5 from 5
from 1 user
(Rate this post)

Check if post exists by Post ID

get_post function: Not the most perfect option!

The get_post function is useful when you want to check if a post exists or not, but it is not the most optimized option.

!is_null( get_post($postId) is working when you want to make sure a post with an ID exists in WordPress:

$postId = 1;
if(!is_null(get_post($postId)){
    //post exists!

}

I wrote a tutorial about the get_post function a while ago, you can read the article to learn how to work with this function deeper:

WordPress Query Posts by Category, Tag, Custom attribute, and more!

But I told you it’s not the best idea to use the get_post function to check if a post exists or not.

Continue reading this article for better options to use when you want to check if a post exists by ID.

get_post_status function: Better choice due to less resource usage

I recommend using the get_post_status function to check if a post exists in WordPress or not.

$postId = 1;
if(get_post_status($postId)) {
    //post exists!

}

post_exists function: Check post existance by title, content, date

The most used WordPress function for post existence status is the post_exists function.

post_exists function syntax

This function determines if a post is existed by title, content, date, type, and status.

If the post_exists function finds any post matching specified options, It’ll return the post ID.

post_exists($title, $content = '', $date = '', $type = '', $status = '')

$title is required but other parameters are optional.

post_exists usage example

In the below example, I tried checking if a post with the title “A title to test” exists or not:

$findPostByTitle = "A title to test";
if(post_exists($findPostByTitle)){
    //post exists!

}

What do you think about "How to Check if a Post Exists in WordPress? (+Example)"?

Your rating submit was successfull.

Your rating submit was not successfull.

Menu