wp_get_canonical_url()
云策文档标注
概述
wp_get_canonical_url() 函数用于获取文章的标准 URL,支持处理分页参数。当文章与当前请求页面相同时,会自动处理分页和评论分页。
关键要点
- 函数返回文章的标准 URL,若文章不存在或未发布则返回 false
- 参数 $post 可选,默认为全局 $post,可以是文章 ID 或 WP_Post 对象
- 如果当前查询对象 ID 与文章 ID 匹配,会处理分页(page)和评论分页(cpage)参数
- 返回值可通过 get_canonical_url 过滤器进行自定义
代码示例
function wp_get_canonical_url( $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
if ( 'publish' !== get_post_status( $post ) ) {
return false;
}
$canonical_url = get_permalink( $post );
// If a canonical is being generated for the current page, make sure it has pagination if needed.
if ( get_queried_object_id() === $post->ID ) {
$page = get_query_var( 'page', 0 );
if ( $page >= 2 ) {
if ( ! get_option( 'permalink_structure' ) ) {
$canonical_url = add_query_arg( 'page', $page, $canonical_url );
} else {
$canonical_url = trailingslashit( $canonical_url ) . user_trailingslashit( $page, 'single_paged' );
}
}
$cpage = get_query_var( 'cpage', 0 );
if ( $cpage ) {
$canonical_url = get_comments_pagenum_link( $cpage );
}
}
/**
* Filters the canonical URL for a post.
*
* @since 4.6.0
*
* @param string $canonical_url The post's canonical URL.
* @param WP_Post $post Post object.
*/
return apply_filters( 'get_canonical_url', $canonical_url, $post );
}注意事项
- 函数在 WordPress 4.6.0 版本中引入
- 相关函数包括 get_queried_object_id()、get_query_var()、get_comments_pagenum_link() 等,用于支持分页和链接生成
- 常用于 rel_canonical() 函数中,为单数查询输出 rel=canonical 标签
原文内容
Returns the canonical URL for a post.
Description
When the post is the same as the current requested page the function will handle the pagination arguments too.
Parameters
$postint|WP_Postoptional-
Post ID or object. Default is global
$post.Default:
null
Source
function wp_get_canonical_url( $post = null ) {
$post = get_post( $post );
if ( ! $post ) {
return false;
}
if ( 'publish' !== get_post_status( $post ) ) {
return false;
}
$canonical_url = get_permalink( $post );
// If a canonical is being generated for the current page, make sure it has pagination if needed.
if ( get_queried_object_id() === $post->ID ) {
$page = get_query_var( 'page', 0 );
if ( $page >= 2 ) {
if ( ! get_option( 'permalink_structure' ) ) {
$canonical_url = add_query_arg( 'page', $page, $canonical_url );
} else {
$canonical_url = trailingslashit( $canonical_url ) . user_trailingslashit( $page, 'single_paged' );
}
}
$cpage = get_query_var( 'cpage', 0 );
if ( $cpage ) {
$canonical_url = get_comments_pagenum_link( $cpage );
}
}
/**
* Filters the canonical URL for a post.
*
* @since 4.6.0
*
* @param string $canonical_url The post's canonical URL.
* @param WP_Post $post Post object.
*/
return apply_filters( 'get_canonical_url', $canonical_url, $post );
}
Hooks
- apply_filters( ‘get_canonical_url’, string $canonical_url, WP_Post $post )
-
Filters the canonical URL for a post.
Changelog
| Version | Description |
|---|---|
| 4.6.0 | Introduced. |