post_link
云策文档标注
概述
post_link 是一个 WordPress 过滤器,用于在 get_permalink() 函数返回处理后的 URL 之前,修改文章(post_type 为 'post')的固定链接。它允许开发者自定义链接格式或添加查询参数。
关键要点
- 仅适用于 post_type 为 'post' 的文章,自定义文章类型应使用 post_type_link 过滤器。
- 参数包括 $permalink(固定链接字符串)、$post(WP_Post 对象)和 $leavename(是否保留文章名称的布尔值)。
- 通过 add_filter() 钩子函数添加自定义回调,可修改链接内容。
代码示例
function append_query_string( $url, $post, $leavename=false ) {
if ( $post->post_type == 'post' ) {
$url = add_query_arg( 'foo', 'bar', $url );
}
return $url;
}
add_filter( 'post_link', 'append_query_string', 10, 3 );注意事项
- 对于其他文章类型,如页面(page)使用 page_link,附件(attachment)使用 attachment_link。
- 分类归档页面可使用 term_link 过滤器。
原文内容
Filters the permalink for a post.
Description
Only applies to posts with post_type of ‘post’.
Parameters
$permalinkstring-
The post’s permalink.
$postWP_Post-
The post in question.
$leavenamebool-
Whether to keep the post name.
Source
return apply_filters( 'post_link', $permalink, $post, $leavename );
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 4 content
Steven Lin
Example migrated from Codex:
Append the query string for posts to permalink URLs (uses add_query_arg):
function append_query_string( $url, $post, $leavename=false ) { if ( $post->post_type == 'post' ) { $url = add_query_arg( 'foo', 'bar', $url ); } return $url; } add_filter( 'post_link', 'append_query_string', 10, 3 );Skip to note 5 content
Anders Norén
For other post types, use the following filters:
page_linkattachment_linkpost_type_linkterm_linkfor archive pages, such as categories.Skip to note 6 content
jmfisherr
/** * Filter to remove a particular slug from post urls */ function remove_slug_from_URL($permalink) { $new_link = str_replace('/slug-to-remove', '', $permalink); return $new_link; } add_filter( 'post_link', 'remove_slug_from_URL', 10, 1);Used to remove parent category slug from permalinks and maintain subcategories in URL