page_link
云策文档标注
概述
page_link 是一个 WordPress 过滤器钩子,用于修改页面的固定链接。它允许开发者基于页面ID或示例状态自定义链接结构。
关键要点
- 过滤器名称:page_link,用于过滤页面的固定链接。
- 参数:$link(页面固定链接字符串)、$post_id(页面ID整数)、$sample(是否为示例链接的布尔值)。
- 源调用:apply_filters('page_link', $link, $post->ID, $sample),在 get_page_link() 函数中触发。
- 相关函数:get_page_link() 用于检索当前页面或页面ID的固定链接。
- 版本历史:自 WordPress 1.5.0 引入。
代码示例
function wpdocs_tutorials_permalink( $permalink, $post ) {
// 确保处理的是页面
if ( 'page' !== get_post_type( $post ) ) {
return $permalink;
}
// 获取页面分配的分类
$categories = get_the_category( $post->ID );
// 检查是否有分类为 "example"
foreach ( $categories as $category ) {
if ( 'example' === $category->slug ) {
return home_url( '/example/' . $post->post_name . '/' );
}
}
// 若无匹配,返回默认固定链接
return $permalink;
}
add_filter( 'page_link', 'wpdocs_tutorials_permalink', 10, 2 );注意事项
此过滤器仅适用于页面(post_type 为 'page'),使用前需验证 post_type。示例代码展示了如何基于分类动态修改链接,但需注意性能影响和分类 slug 的准确性。
原文内容
Filters the permalink for a page.
Parameters
$linkstring-
The page’s permalink.
$post_idint-
The ID of the page.
$samplebool-
Is it a sample permalink.
Source
return apply_filters( 'page_link', $link, $post->ID, $sample );
Changelog
| Version | Description |
|---|---|
| 1.5.0 | Introduced. |
Skip to note 2 content
Noruzzaman
Customizing Permalinks for WordPress Pages Based on Categories
Learn how to dynamically change WordPress page permalinks based on assigned categories. This tutorial will guide you through the process of creating a custom function that checks if a page belongs to a specific category (e.g., “example”) and modifies its permalink structure accordingly. You’ll understand the usage of WordPress hooks and functions like
get_the_category()andadd_filter()to achieve this customization.function wpdocs_tutorials_permalink( $permalink, $post ) { // Ensure we're dealing with a page if ( 'page' !== get_post_type( $post ) ) { return $permalink; } // Get the categories assigned to the page $categories = get_the_category( $post->ID ); // Check if any of the categories is "example" foreach ( $categories as $category ) { if ( 'example' === $category->slug ) { return home_url( '/example/' . $post->post_name . '/' ); } } // Return default permalink if no match return $permalink; } add_filter( 'page_link', 'wpdocs_tutorials_permalink', 10, 2 );