get_page_by_path()
Retrieves a page given its path.
No Hooks.
Return
WP_Post|Array|null
. WP_Post (or array) on success, or null on failure.
Usage
get_page_by_path( $page_path, $output, $post_type );
- $page_path(string) (required)
- Page path.
- $output(string)
- 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)
- Post type or array of post types.
Default: 'page'
Examples
#1 Get the page in it's path
Suppose we have a child page which we access at URL example.com/parent-page/sub-page
: parent-page/sub-page is the page path. Now, somewhere in the code we will get this page.
$page = get_page_by_path( 'parent-page/sub-page' ); //or like this $page = get_page_by_path( '/parent-page/sub-page/' ); print_r( $page );
IMPORTANT: If you specify just a page name, the function will not return anything
$page = get_page_by_path( 'sub-page' ); //> NULL
However, if the page is not a child, then you should specify just the name of the page - the slug.
$page = get_page_by_path( 'page-name' ); //> WP_Post{ ... }
#2 Use with custom post types
There is a new post type, the path to such a post type is usually translated by the name of the post type. For example, the post type is called car
, the URL of the particular post is example.com/car/lada
. To get such a post, you need to use only its shortcut:
// Correct option $page = get_page_by_path( 'lada', OBJECT, 'car' ); // NOT correct (will not return anything) $page = get_page_by_path( 'car/lada', OBJECT, 'car' );
Auto-add attachment type
This function will add the attachment
post type to any instances where the post type is passed as a string. Due to the following code:
if ( is_array( $post_type ) ) { $post_types = $post_type; } else { $post_types = array( $post_type, 'attachment' ); }
If you truly only want to return the item path from only the post type supplied. It needs to be passed as an array like this:
// the query will be: post_type IN ( 'car' ) $page = get_page_by_path( 'lada', OBJECT, ['car'] ); // the query will be: post_type IN ( 'car', 'attachment' ) $page = get_page_by_path( 'lada', OBJECT, 'car' );
This issue was found when an attachment stored in the database had the same path as the page we wanted to retrieve. The attachment having a lower Post ID it is returned first.
Getting the last part of the path
You can use basename() and untrailingslashit() to get the last part of the path:
$page_path = 'car/lada/'; $post_name = basename( untrailingslashit( $page_path ) ); $page = get_page_by_path( $post_name , OBJECT, 'car');
Notes
- Global. wpdb. $wpdb WordPress database abstraction object.
Changelog
Since 2.1.0 | Introduced. |