the_shortlink()
云策文档标注
概述
the_shortlink() 是一个 WordPress 模板标签,用于在循环内显示当前文章的短链接。它输出一个可自定义的链接,默认格式为 /?p=1234,并支持通过插件扩展或第三方服务。
关键要点
- 必须在 The Loop 内调用,用于显示文章的短链接。
- 接受可选参数:$text(链接文本,默认 'This is the short link.')、$title(未使用)、$before(链接前 HTML)、$after(链接后 HTML)。
- 默认仅在启用固定链接时显示,短链接格式为 /?p=文章ID。
- 设计上有限制,旨在由插件提供自定义或第三方短链接服务。
- 输出完整短链接;如需返回短链接字符串,请使用 wp_get_shortlink()。
- 包含过滤器 the_shortlink,允许修改链接的锚标签。
代码示例
function the_shortlink( $text = '', $title = '', $before = '', $after = '' ) {
$post = get_post();
if ( empty( $text ) ) {
$text = __( 'This is the short link.' );
}
$shortlink = wp_get_shortlink( $post->ID );
if ( ! empty( $shortlink ) ) {
$link = '' . $text . '';
/**
* Filters the short link anchor tag for a post.
*
* @since 3.0.0
*
* @param string $link Shortlink anchor tag.
* @param string $shortlink Shortlink URL.
* @param string $text Shortlink's text.
* @param string $title Shortlink's title attribute. Unused.
*/
$link = apply_filters( 'the_shortlink', $link, $shortlink, $text, $title );
echo $before, $link, $after;
}
}注意事项
- 此函数输出链接,而非返回;使用 wp_get_shortlink() 获取短链接字符串。
- 短链接功能可能受插件或主题影响,确保在单篇文章页面使用。
- 参数 $title 在最新版本中已移除,但函数签名仍保留以保持向后兼容。
原文内容
Displays the shortlink for a post.
Description
Must be called from inside “The Loop”
Call like the_shortlink( __( ‘Shortlinkage FTW’ ) )
Parameters
$textstringoptional-
The link text or HTML to be displayed. Defaults to ‘This is the short link.’
$titlestringoptional-
Unused.
$beforestringoptional-
HTML to display before the link. Default empty.
$afterstringoptional-
HTML to display after the link. Default empty.
Source
function the_shortlink( $text = '', $title = '', $before = '', $after = '' ) {
$post = get_post();
if ( empty( $text ) ) {
$text = __( 'This is the short link.' );
}
$shortlink = wp_get_shortlink( $post->ID );
if ( ! empty( $shortlink ) ) {
$link = '<a rel="shortlink" href="' . esc_url( $shortlink ) . '">' . $text . '</a>';
/**
* Filters the short link anchor tag for a post.
*
* @since 3.0.0
*
* @param string $link Shortlink anchor tag.
* @param string $shortlink Shortlink URL.
* @param string $text Shortlink's text.
* @param string $title Shortlink's title attribute. Unused.
*/
$link = apply_filters( 'the_shortlink', $link, $shortlink, $text, $title );
echo $before, $link, $after;
}
}
Hooks
- apply_filters( ‘the_shortlink’, string $link, string $shortlink, string $text, string $title )
-
Filters the short link anchor tag for a post.
Skip to note 4 content
Codex
Custom Text
Displays link with the specified text.
Output:
Shortlinkage FTW
Skip to note 5 content
Codex
Default Usage
Displays link with “This is the short link.” as the text.
Output:
This is the short link.
Skip to note 6 content
Codex
Conditional HTML
Displays link with prefix and suffix HTML that will appear only when the shortlink URL is available.
<li>', '</li></ul>' ); ?> <a href="#" rel="nofollow">short link</a>