函数文档

get_post_permalink()

💡 云策文档标注

概述

get_post_permalink() 函数用于检索自定义文章类型的固定链接。它接受可选参数来控制链接生成,并返回字符串形式的 URL 或 false(如果文章不存在)。

关键要点

  • 函数签名:get_post_permalink( $post = 0, $leavename = false, $sample = false )
  • 参数:$post(文章 ID 或 WP_Post 对象,可选,默认全局 $post)、$leavename(是否保留文章名称,默认 false)、$sample(是否为示例固定链接,默认 false)
  • 返回值:字符串(固定链接 URL)或 false(文章不存在时)
  • 内部处理:基于文章类型、层级结构、重写规则等动态构建链接,支持过滤器 'post_type_link'
  • 相关函数:与 get_permalink() 类似,但专门针对自定义文章类型

代码示例

// 基本用法:获取当前文章的固定链接
$permalink = get_post_permalink();

// 获取指定文章 ID 的固定链接
$permalink = get_post_permalink( 123 );

// 保留文章名称(用于编辑等场景)
$permalink = get_post_permalink( 123, true );

// 获取示例固定链接(预览用)
$permalink = get_post_permalink( 123, false, true );

注意事项

  • 从 WordPress 6.1.0 开始,如果文章不存在,函数返回 false,需进行错误处理
  • 函数内部依赖 WP_Rewrite、文章类型对象等,确保重写规则已正确设置
  • 使用 'post_type_link' 过滤器可自定义链接生成逻辑

📄 原文内容

Retrieves the permalink for a post of a custom post type.

Parameters

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

Default:false

$samplebooloptional
Is it a sample permalink.

Default:false

Return

string|false The post permalink URL. False if the post does not exist.

More Information

Basic Usage

See also get_permalink() .

Source

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

	$post = get_post( $post );

	if ( ! $post ) {
		return false;
	}

	$post_link = $wp_rewrite->get_extra_permastruct( $post->post_type );

	$slug = $post->post_name;

	$force_plain_link = wp_force_plain_post_permalink( $post );

	$post_type = get_post_type_object( $post->post_type );

	if ( $post_type->hierarchical ) {
		$slug = get_page_uri( $post );
	}

	if ( ! empty( $post_link ) && ( ! $force_plain_link || $sample ) ) {
		if ( ! $leavename ) {
			$post_link = str_replace( "%$post->post_type%", $slug, $post_link );
		}
		$post_link = home_url( user_trailingslashit( $post_link ) );
	} else {
		if ( $post_type->query_var && ( isset( $post->post_status ) && ! $force_plain_link ) ) {
			$post_link = add_query_arg( $post_type->query_var, $slug, '' );
		} else {
			$post_link = add_query_arg(
				array(
					'post_type' => $post->post_type,
					'p'         => $post->ID,
				),
				''
			);
		}
		$post_link = home_url( $post_link );
	}

	/**
	 * Filters the permalink for a post of a custom post type.
	 *
	 * @since 3.0.0
	 *
	 * @param string  $post_link The post's permalink.
	 * @param WP_Post $post      The post in question.
	 * @param bool    $leavename Whether to keep the post name.
	 * @param bool    $sample    Is it a sample permalink.
	 */
	return apply_filters( 'post_type_link', $post_link, $post, $leavename, $sample );
}

Hooks

apply_filters( ‘post_type_link’, string $post_link, WP_Post $post, bool $leavename, bool $sample )

Filters the permalink for a post of a custom post type.

Changelog

Version Description
6.1.0 Returns false if the post does not exist.
3.0.0 Introduced.