Checking for existence of a page by title?

The question:

I’m currently working on a plugin, and I essentially want to check if a certain page has been created.

Essentially, I want to do something like this:

    if (file_exists($file)) {
    $exists = true;
} else {
    $exists = false;

But I just want to do it so that it checks, instead, for a post_name value. (If I was further able to ensure that the post was a page and not just a post with that title, that would be great too.)

How do I do this?

I had been getting the script to grab the headers from the url of the post and if it returned a 404, to return $exists = false, but I’ve pinpointed a memory leak problem with that and I don’t think it’s very efficient.

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Using get_page_by_title() along the line of below exemplary code should work:

if ( get_page_by_title( $page_title, $output, $post_type ) == NULL ) {
    $exists = false;
} else {
    $exists = true;


  • $page_title is obviously what you are looking for;
  • $output can be OBJECT, ARRAY_N or ARRAY – Default: OBJECT;
  • $post_type can be specified, in your case its not needed, because the default value is page;
  • Returns NULL if no post with the title is found;
  • For the inner logic take a look at the source.

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment