Checking for existence of a page by title?

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:

Read More
    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.

Related posts

Leave a Reply

1 comment

  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;
    }
    

    Explanation:

    • $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.