返回帖子,页面,附件或网站的短链接。
原型
wp_get_shortlink( int $id, string $context = 'post', bool $allow_slugs = true )
描述
此函数用于提供所有主题和插件可以定位的短链接标记。插件必须挂钩才能提供实际的短链接。默认短链接支持仅限于为帖子提供?p =样式链接。插件可以通过’pre_get_shortlink’过滤器使此功能短路,或通过’get_shortlink’过滤器过滤输出。
参数
$id
(int)
(Optional)
帖子或网站ID。默认值为0,表示当前帖子或站点。
$context
(string)
(Optional)
该ID是“网站”ID,“发布”ID还是“媒体”ID。如果是’post’,则会查询帖子的post_type。如果是’query’,则查询当前查询以确定id和context。
$allow_slugs
(bool)
(Optional)
是否允许短链接中的后期slu ..由插件决定如何以及是否尊重这一点。
返回值
(string)
如果请求的资源没有短链接或者未启用短链接,则为短链接或空字符串。
源文件
路径:wp-includes/link-template.php
<?php
...
function wp_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) {
/**
* Filters whether to preempt generating a shortlink for the given post.
*
* Passing a truthy value to the filter will effectively short-circuit the
* shortlink-generation process, returning that value instead.
*
* @since 3.0.0
*
* @param bool|string $return Short-circuit return value. Either false or a URL string.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink.
*/
$shortlink = apply_filters( 'pre_get_shortlink', false, $id, $context, $allow_slugs );
if ( false !== $shortlink ) {
return $shortlink;
}
$post_id = 0;
if ( 'query' == $context && is_singular() ) {
$post_id = get_queried_object_id();
$post = get_post( $post_id );
} elseif ( 'post' == $context ) {
$post = get_post( $id );
if ( ! empty( $post->ID ) )
$post_id = $post->ID;
}
$shortlink = '';
// Return p= link for all public post types.
if ( ! empty( $post_id ) ) {
$post_type = get_post_type_object( $post->post_type );
if ( 'page' === $post->post_type && $post->ID == get_option( 'page_on_front' ) && 'page' == get_option( 'show_on_front' ) ) {
$shortlink = home_url( '/' );
} elseif ( $post_type->public ) {
$shortlink = home_url( '?p=' . $post_id );
}
}
/**
* Filters the shortlink for a post.
*
* @since 3.0.0
*
* @param string $shortlink Shortlink URL.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink. Not used by default.
*/
return apply_filters( 'get_shortlink', $shortlink, $id, $context, $allow_slugs );
}
...
?>
其他
英文文档:https://developer.wordpress.org/reference/functions/wp_get_shortlink/