禁用WordPress识别路径为附件
1 个回答
- 投票数
在对默认永久结构及其修改方法有了更多了解之后,我偶然发现了rewrite_rules_array
钩子.该挂钩可让您过滤重写规则数组,WordPress中的URL重写规则数组,这将有助于确定要加载的内容类型.
这是禁用将路径识别为附件的默认行为的好地方.这样,您就可以摆脱所有附件的重写规则,从而摆脱将路径识别为附件的所有行为.
add_filter('rewrite_rules_array', function($rules) {
foreach ($rules as $rule => $url) {
if (strpos($url, 'attachment') !== false) {
unset($rules[$rule]);
}
}
return $rules;
});
我不确定所有其他规则,我当然想全部检查一下.例如:
"(.?.+?)(?:/([0-9]+))?/?$" => "index.php?pagename=$matches[1]&page=$matches[2]"
"([^/]+)(?:/([0-9]+))?/?$" => "index.php?name=$matches[1]&page=$matches[2]"
将帮助您识别页面,这对于了解您是否只想使用页面非常有用.但是请记住,如果仅使用这些键/值重写数组,则新规则(例如,自定义帖子类型的规则)也将被重写(删除).
注意::只有在WordPress后端的"设置">"永久链接"页面上,才能调试此过滤器.
After getting to know a bit more about the default perma structure and how to modify it I stumbled upon the hook rewrite_rules_array
. This hook allows you to filter the array of rewrite rules, an array of URL rewrite rules in WordPress what will help determine what type of content to load.
This is a great place to disable the default behavior for recognizing the path as attachment. This is how you get rid of all rewrite rules for attachments, thus all the behavior for recognizing a path as attachment.
add_filter('rewrite_rules_array', function($rules) {
foreach ($rules as $rule => $url) {
if (strpos($url, 'attachment') !== false) {
unset($rules[$rule]);
}
}
return $rules;
});
I'm not sure about all other rules and I definitely want to check them all out. These for example:
"(.?.+?)(?:/([0-9]+))?/?$" => "index.php?pagename=$matches[1]&page=$matches[2]"
"([^/]+)(?:/([0-9]+))?/?$" => "index.php?name=$matches[1]&page=$matches[2]"
Will help you recognize pages, very useful to know if you only want to use pages. But remember if you rewrite the array with only these keys/values then new rules for example rules for your custom post type will also be rewritten (removed).
NOTE: Debugging this filter is only possible on the Settings > Permalinks page in the WordPress back-end.
每当您输入不存在两个路径段的URL时,WordPress都会自动将查询解析为附件.
如何繁殖
/%postname%/
./foo/bar
确保"foo"不是现有的分类法或帖子类型.pre_get_posts
并转储global $wp_query
.post_type = 'attachment'
以及其他一些与附件相关的信息.注意:我不确定我在第2步和第5步中所做的陈述.
为什么要照顾?
我发现处理这种默认行为非常烦人,并且真的想以某种方式禁用它,如果您知道如何请告诉我.这使得无法实现某些永久链接结构.您可能还想知道的地方.我正在尝试实现一个永久链接结构,其中当前后段塞以术语段塞作为前缀.例如,帖子类型"example"具有帖子"bar",该帖子与带有"foo"的词条有关系.代替定义永久链接"example/bar",应将其定义为"foo/bar".