Skip to main content

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
<?php
// Define the full URL of the page
$page_url = 'https://example.com/about-us/our-team/';

// Extract the path from the URL
$path = parse_url( $page_url, PHP_URL_PATH );

// Remove leading/trailing slashes and any file extensions if present
$path = trim( $path, '/' );
$path = preg_replace( '/\.(php|html)$/', '', $path ); // Remove .php or .html if present

// Get the page object by its path
$page = get_page_by_path( $path );

if ( $page ) {
    // Page found, you can now access its properties
    echo 'Page Title: ' . $page->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_urlThis 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 CheckThe 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_titleIDpost_content, etc.
This method allows you to reliably retrieve a WordPress page object using its permalink structure.