函数文档

_get_page_link()

💡 云策文档标注

概述

_get_page_link() 是 WordPress 内部函数,用于获取页面(非首页)的固定链接,忽略 page_on_front 设置。它根据页面结构和参数生成链接,适用于开发者处理页面链接逻辑。

关键要点

  • 函数返回页面固定链接字符串,忽略 page_on_front 设置,仅内部使用。
  • 参数包括 $post(页面 ID 或对象,默认全局 $post)、$leavename(是否保留页面名称,默认 false)和 $sample(是否作为示例链接处理,默认 false)。
  • 使用 WP_Rewrite 获取页面结构,根据条件生成带或不带页面名称的链接,或回退到查询字符串形式。
  • 通过 apply_filters('_get_page_link', $link, $post_id) 钩子允许过滤链接。

代码示例

function _get_page_link( $post = 0, $leavename = false, $sample = false ) {
    global $wp_rewrite;

    $post = get_post( $post );

    $force_plain_link = wp_force_plain_post_permalink( $post );

    $link = $wp_rewrite->get_page_permastruct();

    if ( ! empty( $link ) && ( ( isset( $post->post_status ) && ! $force_plain_link ) || $sample ) ) {
        if ( ! $leavename ) {
            $link = str_replace( '%pagename%', get_page_uri( $post ), $link );
        }

        $link = home_url( $link );
        $link = user_trailingslashit( $link, 'page' );
    } else {
        $link = home_url( '?page_id=' . $post->ID );
    }

    return apply_filters( '_get_page_link', $link, $post->ID );
}

注意事项

  • 此函数为内部函数,不建议在主题或插件中直接调用,应使用 get_page_link() 替代。
  • 忽略 page_on_front,适用于非首页页面链接生成。
  • 返回的链接可能包含尾部斜杠,取决于站点设置。

📄 原文内容

Retrieves the page permalink.

Description

Ignores page_on_front. Internal use only.

Parameters

$postint|WP_Postoptional
Post ID or object. Default uses the global $post.
$leavenamebooloptional
Whether to keep the page name.

Default:false

$samplebooloptional
Whether it should be treated as a sample permalink.

Default:false

Return

string The page permalink.

Source

function _get_page_link( $post = 0, $leavename = false, $sample = false ) {
	global $wp_rewrite;

	$post = get_post( $post );

	$force_plain_link = wp_force_plain_post_permalink( $post );

	$link = $wp_rewrite->get_page_permastruct();

	if ( ! empty( $link ) && ( ( isset( $post->post_status ) && ! $force_plain_link ) || $sample ) ) {
		if ( ! $leavename ) {
			$link = str_replace( '%pagename%', get_page_uri( $post ), $link );
		}

		$link = home_url( $link );
		$link = user_trailingslashit( $link, 'page' );
	} else {
		$link = home_url( '?page_id=' . $post->ID );
	}

	/**
	 * Filters the permalink for a non-page_on_front page.
	 *
	 * @since 2.1.0
	 *
	 * @param string $link    The page's permalink.
	 * @param int    $post_id The ID of the page.
	 */
	return apply_filters( '_get_page_link', $link, $post->ID );
}

Hooks

apply_filters( ‘_get_page_link’, string $link, int $post_id )

Filters the permalink for a non-page_on_front page.

Changelog

Version Description
2.1.0 Introduced.