函数文档

the_permalink()

💡 云策文档标注

概述

the_permalink() 是 WordPress 模板标签,用于在 The Loop 中显示当前文章的固定链接。它直接输出链接,适用于循环内显示每篇文章的链接,但不能用于显示任意文章的链接。

关键要点

  • 必须在 The Loop 中使用,用于显示当前处理文章的固定链接。
  • 参数 $post 可选,可以是文章 ID 或 WP_Post 对象,默认为全局 $post。
  • 通过 the_permalink 过滤器可自定义链接显示,函数内部调用 get_permalink() 获取链接并应用 esc_url() 清理。
  • 与 get_permalink() 不同,the_permalink() 直接输出链接,而 get_permalink() 返回链接字符串,适用于获取任意文章的链接。

代码示例

// 在循环中显示文章标题作为链接文本
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>

// 使用自定义文本作为链接
<a href="<?php the_permalink(); ?>">permalink</a>

// 仅显示链接文本,不创建链接
This address for this post is: <?php the_permalink(); ?>

注意事项

  • 不能用于显示非当前文章的链接,需使用 get_permalink() 配合文章 ID。
  • 输出前已应用 esc_url() 确保 URL 安全,无需额外转义。
  • 自 WordPress 4.4.0 起添加 $post 参数,允许指定文章。

📄 原文内容

Displays the permalink for the current post.

Parameters

$postint|WP_Postoptional
Post ID or post object. Default is the global $post.

More Information

This tag must be within The Loop, and is generally used to display the permalink for each post, when the posts are being displayed. Since this template tag is limited to displaying the permalink for the post that is being processed, you cannot use it to display the permalink to an arbitrary post on your weblog. Refer to get_permalink() if you want to get the permalink for a post, given its unique post id.

Source

function the_permalink( $post = 0 ) {
	/**
	 * Filters the display of the permalink for the current post.
	 *
	 * @since 1.5.0
	 * @since 4.4.0 Added the `$post` parameter.
	 *
	 * @param string      $permalink The permalink for the current post.
	 * @param int|WP_Post $post      Post ID, WP_Post object, or 0. Default 0.
	 */
	echo esc_url( apply_filters( 'the_permalink', get_permalink( $post ), $post ) );
}

Hooks

apply_filters( ‘the_permalink’, string $permalink, int|WP_Post $post )

Filters the display of the permalink for the current post.

Changelog

Version Description
4.4.0 Added the $post parameter.
1.2.0 Introduced.

User Contributed Notes