函数文档

get_page_uri()

💡 云策文档标注

概述

get_page_uri() 函数用于构建页面的 URI 路径,自动包含父级页面以形成完整路径,无论是否配置了“漂亮”固定链接。

关键要点

  • 函数接受 WP_Post 对象、整数或可选参数(默认为全局 $post),返回页面 URI 字符串或错误时 false
  • 子页面的 URI 会以父级页面 post_name 为“目录”结构拼接,例如 top-level-page/sub-page/current-page
  • 内部通过遍历 $page->ancestors 数组递归构建路径,并应用 get_page_uri 过滤器进行自定义
  • 与 get_post()、get_sample_permalink() 等相关函数配合使用,适用于页面链接生成场景

代码示例

$page_id = 5;
$uri = get_page_uri( $page_id );
echo '<a href="' . esc_url( $uri ) . '">' . esc_html__( "The Page", "textdomain" ) . '</a>';

📄 原文内容

Builds the URI path for a page.

Description

Sub pages will be in the “directory” under the parent page post name.

Parameters

$pageWP_Post|object|intoptional
Page ID or WP_Post object. Default is global $post.

Return

string|false Page URI, false on error.

More Information

If the page has parents, those are prepended to the URI to provide a full path. For example, a third level page might return a URI like this:

top-level-page/sub-page/current-page

This function will return a “slug” style URI regardless of whether “pretty” Permalinks are configured.

Source

function get_page_uri( $page = 0 ) {
	if ( ! $page instanceof WP_Post ) {
		$page = get_post( $page );
	}

	if ( ! $page ) {
		return false;
	}

	$uri = $page->post_name;

	foreach ( $page->ancestors as $parent ) {
		$parent = get_post( $parent );
		if ( $parent && $parent->post_name ) {
			$uri = $parent->post_name . '/' . $uri;
		}
	}

	/**
	 * Filters the URI for a page.
	 *
	 * @since 4.4.0
	 *
	 * @param string  $uri  Page URI.
	 * @param WP_Post $page Page object.
	 */
	return apply_filters( 'get_page_uri', $uri, $page );
}

Hooks

apply_filters( ‘get_page_uri’, string $uri, WP_Post $page )

Filters the URI for a page.

Changelog

Version Description
4.6.0 The $page parameter was made optional.
1.5.0 Introduced.

User Contributed Notes