9

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
  • 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
    Commented Sep 10, 2014 at 21:48

1 Answer 1

10

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.

1
  • Is there something like this but for multisite?
    – chifliiiii
    Commented Oct 29, 2020 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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