最近在开发一个WordPress项目时,我遇到了一个让人头疼的问题。客户希望网站能有非常灵活的URL结构,比如
events/upcoming/page/2
blog/category-name/author/john-doe
add_rewrite_rule
functions.php
就在我快要放弃,准备硬着头皮写一堆条件判断时,我发现了
upstatement/routes
upstatement/routes
upstatement/routes
Routes::map()
首先,通过Composer安装这个插件:
<pre class="brush:php;toolbar:false;">composer require upstatement/routes
安装完成后,你就可以在你的
functions.php
一个常见的场景:自定义分页和内容类型
假设你有一个名为“新闻”的自定义文章类型,你希望它的分页URL是
news/:category/page/:pg
upstatement/routes
<pre class="brush:php;toolbar:false;">// functions.php
use Upstatement\Routes;
Routes::map('news/:category/page/:pg', function($params) {
// 从URL中获取分类和页码参数
$category_slug = $params['category'];
$page_number = intval($params['pg']);
// 构建一个自定义的WP_Query查询
$query_args = [
'post_type' => 'news', // 假设你的自定义文章类型是 'news'
'posts_per_page' => 10,
'paged' => $page_number,
'tax_query' => [ // 根据分类别名查询
[
'taxonomy' => 'news_category', // 假设你的分类法是 'news_category'
'field' => 'slug',
'terms' => $category_slug,
],
],
];
// 加载 archive-news.php 模板,并将查询结果传递给它
// 还可以传递额外的参数到模板中,例如标题
Routes::load('archive-news.php', ['custom_title' => '新闻分类:' . $category_slug], $query_args, 200);
});在这个例子中:
Routes::map('news/:category/page/:pg', ...)news/any-category-slug/page/any-number
$params
category
pg
WP_Query
Routes::load('archive-news.php', ...)archive-news.php
custom_title
在
archive-news.php
$wp_query
global $params;
Routes::load
$params['custom_title']
另一个例子:为自定义事件详情页创建美观URL
假设你有一个自定义文章类型
event
events/:event-slug
<pre class="brush:php;toolbar:false;">// functions.php
use Upstatement\Routes;
Routes::map('events/:event', function($params) {
$event_slug = $params['event'];
// 根据slug获取事件文章对象
$event_post = get_page_by_path($event_slug, OBJECT, 'event');
if ($event_post) {
// 加载 single-event.php 模板,并传递事件数据
Routes::load('single-event.php', ['event_data' => $event_post], null, 200);
} else {
// 如果找不到事件,返回404
Routes::load('404.php', null, null, 404);
}
});这个例子展示了如何捕获一个动态的事件slug,然后根据这个slug查询对应的文章,并加载一个特定的模板。如果事件不存在,还可以优雅地处理404错误。
upstatement/routes
Routes::map()
Routes::load()
upstatement/routes
WP_Query
Routes::load()
总而言之,
upstatement/routes
以上就是告别WordPress死板路由:如何使用upstatement/routes插件打造灵活URL结构的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号