There may be a situation when you need to display content based on existence of a page or non-hierarchical custom post by url. As the example below there are two different parent pages for the same page slug. We assume that certain pages will have the same title, and just have different parent pages. So we want to check if a page exists by url?
1 2 | http://example.com/audits/third-quarter-report http://example.com/banking/third-quarter-report |
check if a page exists by url
For the existence for a page, we can make a list of paths of paths to check
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | $page_paths = array( 'audits/third-quarter-report', 'banking/third-quarter-report' ); foreach($page_paths as $page_path){ $page = get_page_by_path($page_path); if(!$page){ echo '<code>'.$page_path.'</code> Does not exist.'; } else{ echo '<code>'.$page_path.'</code> Exists and resolves to: <code>'.get_permalink($page->ID).'</code>'; } } |
The get_page_by_path() function is quite handy in such case which retrieves a page given its path. You can also check if a custom post of non-hierarchical custom post types exists by url through providing third parameter to this function in the same manner.