Using WordPress ‘get_page_by_path()’ PHP function

The get_page_by_path() WordPress PHP function retrieves a page given its path.

Usage

get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' )

Example:

Input:

get_page_by_path('about-us', OBJECT, 'page');

Output:

A WP_Post object of the ‘about-us’ page.

Parameters

  • $page_path (string) – Required. The page path (e.g., ‘parent-page/sub-page’).
  • $output (string) – Optional. The required return type. One of OBJECT, ARRAY_A, or ARRAY_N, which correspond to a WP_Post object, an associative array, or a numeric array, respectively. Default: OBJECT.
  • $post_type (string|array) – Optional. Post type or array of post types. Default ‘page’. Default: ‘page’.

More information

See WordPress Developer Resources: get_page_by_path()

Examples

Retrieve a page by its path

Retrieve the ‘about-us’ page using its path.

$page = get_page_by_path('about-us');

Retrieve a page as an associative array

Retrieve the ‘about-us’ page as an associative array.

$page_array = get_page_by_path('about-us', ARRAY_A);

Retrieve a custom post type by its path

Retrieve a custom post type ‘product’ with the path ‘product-1’.

$product = get_page_by_path('product-1', OBJECT, 'product');

Retrieve a page only, excluding attachments

Retrieve the ‘about-us’ page, excluding attachments.

$page = get_page_by_path('about-us', OBJECT, array('page'));

Retrieve a page in a nested hierarchy

Retrieve a child page ‘team’ under the parent page ‘about-us’.

$child_page = get_page_by_path('about-us/team');