# WordPress get page by url
To get a WordPress page by its URL, you can use the `get_page_by_path()` function. This function retrieves a page object based on its slug or full path.
Here's how to use it:
Code
``` post_title; echo 'Page ID: ' . $page->ID; // You can access other properties like $page->post_content, $page->post_status, etc. } else { echo 'Page not found for the given URL.'; } ?> ```
Explanation:
- `$page_url`: This variable holds the full URL of the page you want to retrieve. - `parse_url( $page_url, PHP_URL_PATH )`: This extracts only the path component from the full URL (e.g., `/about-us/our-team/`). - `trim( $path, '/' )`: This removes any leading or trailing slashes from the path. - `preg_replace( '/\.(php|html)$/', '', $path )`: This removes any common file extensions like `.php` or `.html` if they are present in the path. This ensures you're left with the clean slug or path that WordPress uses. - `get_page_by_path( $path )`: This is the core WordPress function. It takes the cleaned path (or slug) as an argument and returns the corresponding page object if found. If no page matches the path, it returns `null`. - **Conditional Check**: The code then checks if a page object was returned. If `$page` is not `null`, it means the page was found, and you can access its properties like `post_title`, `ID`, `post_content`, etc.
This method allows you to reliably retrieve a WordPress page object using its permalink structure.