Function and usage of get_page_by_path() in wordpress


Answers ( 1 )


    The get_page_by_path() function in WordPress is a useful utility for retrieving a page or post based on its path. Here's a detailed explanation and sample usage:


    get_page_by_path( string $page_path, string $output = OBJECT, string|array $post_type = ‘page’ ): WP_Post|array|null


    This function retrieves a page or post from the WordPress database given its path.


    1. $page_path (string, required): The relative path of the page. This is typically the URL slug of the page or post. For example, in, the $page_path would be 'about-us'.

    2. $output (string, optional): Determines the format of the returned data. There are three possible values:

      • OBJECT: The default value. Returns a WP_Post object.
      • ARRAY_A: Returns an associative array.
      • ARRAY_N: Returns a numeric array.
    3. $post_type (string|array, optional): Specifies the type of post to retrieve. By default, it is set to 'page'. However, you can also pass other post types or an array of post types.


    • The function returns a WP_Post object, an array, or null.
    • If the page is found, it returns a WP_Post object or an array based on the $output parameter.
    • If no page is found, it returns null.

    Sample Usage:

    Here's how you might use get_page_by_path() in a WordPress template or plugin:

    // Assume you want to retrieve the 'about-us' page
    $page_path = 'about-us';
    // Get the page as a WP_Post object
    $about_page = get_page_by_path($page_path);
    if ( $about_page ) {
        // The page exists
        echo 'Title: ' . $about_page->post_title;
        echo 'Content: ' . $about_page->post_content;
    } else {
        // No page found
        echo 'No page found with the given path.';

    In this example, the function is used to retrieve the 'about-us' page. If the page is found, it prints the title and content of the page. If no page is found, it displays a message indicating that no page was found. This function is extremely useful for custom templates and plugins where you need to fetch page content based on a known path.

Leave an answer