Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.
share|improve this answer
    
Thanks so much. That seems like the perfect solution. However, where exactly do I call the page title from my script? It will be in the $temp_output variable. Should it be $page_title = $temp_output? Sorry for my obvious don't-know-what-the-hell-I'm-doing question. –  Edmund Heaphy Jun 27 at 15:47
    
In short, the $page_title in above get_page_by_title() call is just a not the variable name you can use. Meaning you can use whatever you want, like $temp_output if it holds your information - or you don't use a variable and input the parameter directly as a string, like 'the title you want'. You only need the 1st parameter - $page_title - the 2nd and 3rd are optional, as they have a default value. So get_page_by_title( $temp_output ) should do it, provided that you have the variable inside your script/function scope available. Hope that helps. @EdmundHeaphy –  ialocin Jun 27 at 21:08
    
Thank you! That is absolutely magnificent and works like a charm. And no memory leaks either. Thanks so much. –  Edmund Heaphy Jun 27 at 22:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.