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:

    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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

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.


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x