get_page_by_path()
get_page_by_path( string $page_path, string $output = O…
get_page_by_path( string $page_path, string $output = OBJECT, string|array $post_type = ‘page’ )
检索给定路径的页。
Retrieves a page given its path.
目录锚点:#参数#返回#源码#笔记
参数(Parameters)
参数 | 类型 | 必填 | 说明 |
---|---|---|---|
$page_path | (string) | 必需 | 页面路径。 |
$output | (string) | 可选 | 所需的返回类型。数组或数组中的一个,分别对应于WP后对象、关联数组或数值数组。 |
$post_type | (string | array) | 可选 | Post类型或Post类型数组。 |
返回(Return)
(WP|Post|array|null)成功时为WP|Post(WP|Post|array|null),失败时为null。
源码(Source)
/** * Retrieves a page given its path. * * @since 2.1.0 * * @global wpdb $wpdb WordPress database abstraction object. * * @param string $page_path Page path. * @param string $output Optional. Output type. Accepts OBJECT, ARRAY_N, or ARRAY_A. * Default OBJECT. * @param string|array $post_type Optional. Post type or array of post types. Default 'page'. * @return WP_Post|array|void WP_Post on success. */ function get_page_by_path( $page_path, $output = OBJECT, $post_type = 'page' ) { global $wpdb; $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 = esc_sql( $parts ); $parts = array_map( 'sanitize_title_for_query', $parts ); $in_string = "'" . implode( "','", $parts ) . "'"; if ( is_array( $post_type ) ) { $post_types = $post_type; } else { $post_types = array( $post_type, 'attachment' ); } $post_types = esc_sql( $post_types ); $post_type_in_string = "'" . implode( "','", $post_types ) . "'"; $sql = " SELECT ID, post_name, post_parent, post_type FROM $wpdb->posts WHERE post_name IN ($in_string) AND post_type IN ($post_type_in_string) "; $pages = $wpdb->get_results( $sql, OBJECT_K ); $revparts = array_reverse( $parts ); $foundid = 0; foreach ( (array) $pages as $page ) { if ( $page->post_name == $revparts[0] ) { $count = 0; $p = $page; while ( $p->post_parent != 0 && isset( $pages[ $p->post_parent ] ) ) { $count++; $parent = $pages[ $p->post_parent ]; if ( ! isset( $revparts[ $count ] ) || $parent->post_name != $revparts[ $count ] ) break; $p = $parent; } if ( $p->post_parent == 0 && $count+1 == count( $revparts ) && $p->post_name == $revparts[ $count ] ) { $foundid = $page->ID; if ( $page->post_type == $post_type ) break; } } } if ( $foundid ) { return get_post( $foundid, $output ); } }
更新版本 | 源码位置 | 使用 | 被使用 |
---|---|---|---|
2.1.0 | wp-includes/post.php:4922 | 9 | 6 |
笔记(Notes)
页面路径
如果未指定post_类型,则它将同时搜索页面和附件。
类别:WordPress 函数手册、
本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。
还没有任何评论,赶紧来占个楼吧!