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.
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.
Skip to note 4 content
Codex
Used as Link With Title Tag
Creates a link for the permalink, with the post’s title as the link text. This is a common way to put the post’s title.
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"></a>Skip to note 5 content
Codex
As Link With Text
You can use whatever text you like as the link text, in this case, “permalink”.
<a href="<?php the_permalink(); ?>">permalink</a>Skip to note 6 content
Codex
Display Post URL as Text
Displays the URL to the post, without creating a link:
This address for this post is: