wpseek.com
A WordPress-centric search engine for devs and theme authors



get_page_by_path › WordPress Function

Since2.1.0
Deprecatedn/a
get_page_by_path ( $page_path, $output = OBJECT, $post_type = 'page' )
Parameters: (3)
  • (string) $page_path Page path.
    Required: Yes
  • (string) $output 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.
    Required: No
    Default: OBJECT
  • (string|array) $post_type Optional. Post type or array of post types. Default 'page'.
    Required: No
    Default: 'page'
Returns:
  • (WP_Post|array|null) WP_Post (or array) on success, or null on failure.
Defined at:
Codex:

Retrieves a page given its path.



Source

function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) {
	$page_path = rawurlencode( urldecode( $page_path ) );
	$page_path = str_replace( '%2F', '/', $page_path );
	$page_path = str_replace( '%20', ' ', $page_path );
	$parts     = explode( '/', trim( $page_path, '/' ) );
	$parts     = array_map( 'sanitize_title_for_query', $parts );

	if ( is_array( $post_type ) ) {
		$post_types = $post_type;
	} else {
		$post_types = array( $post_type, 'attachment' );
	}

	$args = array(
		'post_name__in'          => $parts,
		'post_type'              => $post_types,
		'post_status'            => 'all',
		'posts_per_page'         => -1,
		'update_post_term_cache' => false,
		'update_post_meta_cache' => false,
		'no_found_rows'          => true,
		'orderby'                => 'none',
	);

	$query = new WP_Query( $args );
	$posts = $query->get_posts();
	$pages = array();

	foreach ( $posts as $post ) {
		$pages[ $post->ID ] = $post;
	}

	$revparts = array_reverse( $parts );

	$foundid = 0;
	foreach ( $pages as $page ) {
		if ( $page->post_name == $revparts[0] ) {
			$count = 0;
			$p     = $page;

			/*
			 * Loop through the given path parts from right to left,
			 * ensuring each matches the post ancestry.
			 */
			while ( 0 != $p->post_parent && isset( $pages[ $p->post_parent ] ) ) {
				$count++;
				$parent = $pages[ $p->post_parent ];
				if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] ) {
					break;
				}
				$p = $parent;
			}

			if ( 0 == $p->post_parent && count( $revparts ) == $count + 1 && $p->post_name == $revparts[ $count ] ) {
				$foundid = $page->ID;
				if ( $page->post_type == $post_type ) {
					break;
				}
			}
		}
	}

	if ( $foundid ) {
		return get_post( $foundid, $output );
	}

	return null;
}