8

I need to display certain content depending on whether or not a page URL exists. I don't want to check by title, because certain pages will have the same title, and just different parent pages.

For example one page may be:

  1. http://example.com/analysis/firstNamelastName
  2. http://example.com/exercise/firstNamelastName

I just need to know if one of these URL exists or not.

  • 1
    analysis and exercise are categories? I'm not sure your approach is the best and I'm trying to understand what you want – Tomás Cot Sep 10 '14 at 21:48
9

You could make a list of paths to check...

$page_paths = array(
    'analysis/firstNamelastName',
    'exercise/firstNamelastName'
);

Then check if there's a page object for each of the page paths.

foreach( $page_paths as $page_path ) {

    echo '<code>' . $page_path . '</code> ' . PHP_EOL;

    if( ! $page = get_page_by_path( $page_path ) ){
        echo 'Does not exist.' . PHP_EOL;
    } else{
        echo 'Exists and resolves to: <code>' . get_permalink( $page->ID ) . '</code>' . PHP_EOL;
    }  

}

You can actually use get_page_by_path(); for Post Types other than page. See the third parameter.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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