函数文档

get_page_link()

💡 云策文档标注

概述

get_page_link() 函数用于获取指定页面或当前页面的固定链接,支持处理首页设置(page_on_front)。开发者可通过参数控制是否保留页面名称或作为示例链接。

关键要点

  • 函数返回页面的固定链接字符串,尊重 WordPress 的首页设置(show_on_front 和 page_on_front)。
  • 参数包括 $post(页面 ID 或对象,默认使用全局 $post)、$leavename(是否保留页面名称,默认 false)和 $sample(是否作为示例链接,默认 false)。
  • 内部使用 _get_page_link() 和 home_url() 生成链接,并通过 'page_link' 过滤器允许自定义。
  • 相关函数包括 _get_page_link()、home_url()、apply_filters()、get_option() 和 get_post()。

代码示例

// 获取博客页面 ID 的固定链接示例
$page_for_posts = get_option('page_for_posts');
$link = get_page_link($page_for_posts);
echo $link;

注意事项

  • 当页面被设置为首页时,函数返回首页 URL(home_url('/'))。
  • 确保传入有效的 $post 参数以避免错误,可使用 get_post() 辅助。
  • 过滤器 'page_link' 可用于修改链接输出,参数包括 $link、$post_id 和 $sample。

📄 原文内容

Retrieves the permalink for the current page or page ID.

Description

Respects page_on_front. Use this one.

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 ) {
	$post = get_post( $post );

	if ( 'page' === get_option( 'show_on_front' ) && (int) get_option( 'page_on_front' ) === $post->ID ) {
		$link = home_url( '/' );
	} else {
		$link = _get_page_link( $post, $leavename, $sample );
	}

	/**
	 * Filters the permalink for a page.
	 *
	 * @since 1.5.0
	 *
	 * @param string $link    The page's permalink.
	 * @param int    $post_id The ID of the page.
	 * @param bool   $sample  Is it a sample permalink.
	 */
	return apply_filters( 'page_link', $link, $post->ID, $sample );
}

Hooks

apply_filters( ‘page_link’, string $link, int $post_id, bool $sample )

Filters the permalink for a page.

Changelog

Version Description
1.5.0 Introduced.

User Contributed Notes