WordPress.org

Codex

Interested in functions, hooks, classes, or methods? Check out the new WordPress Code Reference!

Function Reference/get page by path

Description

Retrieves a page or other post object given its path.

Usage

<?php get_page_by_path$page_path$output$post_type ); ?>

Parameters

$page_path
(string) (required) Page path.
Default: None
$output
(string) (optional) Output type. OBJECT, ARRAY_N, or ARRAY_A.
Default: OBJECT
$post_type
(string or array) (optional) Post type or array of post types.
Default: 'page'

Return Values

(WP_Post|null) 
WP_Post on success or null on failure.

Examples

Page Path

This is the equivalent of the 'pagename' query, as in: 'index.php?pagename=parent-page/sub-page'.

Code for the above could be written as (assuming 'parent-page/sub-page' is actually the path to a page):

get_page_by_path('parent-page/sub-page');

For non-hierarchical custom post types, you need to use just the slug in tandem with the post_type parameter.

//Returns nothing, assumes animals is the rewrite slug for the animal CPT
get_page_by_path('animals/cat', OBJECT, 'animal');

//Returns the animal with the slug 'cat'
get_page_by_path('cat', OBJECT, 'animal');

The functions basename() and untrailingslashit() are handy for grabbing the last part of the URL for this:

$page_path = 'animals/cat/';
get_page_by_path( basename( untrailingslashit( $page_path ) ) , OBJECT, 'animal');

Notes

  • Uses global: (object) $wpdb
  • Returns false for "private" pages/posts

Change Log

Since: 2.1.0

Source File

get_page_by_path() is located in wp-includes/post.php.

Related

Page Tags: get_all_page_ids(), get_ancestors(), get_page(), get_page_link(), get_page_by_path(), get_page_by_title(), get_page_children(), get_page_hierarchy(), get_page_uri(), get_pages(), is_page(), page_uri_index(), wp_list_pages(), wp_page_menu()

See also index of Function Reference and index of Template Tags.