upstatement / routes
使用这个简单的插件管理WordPress中的重写和路由
Requires
- php: >=5.6.0|7.*
- altorouter/altorouter: ^2.0.2
- composer/installers: ^1.0 || ^2.0
Requires (Dev)
- phpunit/phpunit: 5.7.16
- satooshi/php-coveralls: *
- wp-cli/wp-cli: *
README
WordPress的简单路由。专为与 Timber 使用设计
基本用法
/* functions.php */ Routes::map('myfoo/bar', 'my_callback_function'); Routes::map('my-events/:event', function($params) { $event_slug = $params['event']; $event = new ECP_Event($event_slug); $query = new WPQuery(); //if you want to send a custom query to the page's main loop Routes::load('single.php', array('event' => $event), $query, 200); });
使用路由可以轻松实现自定义分页 — 以及你在最疯狂的URL和参数幻想中可能想到的一切。OMG太简单了!
一些例子
在你的 functions.php 文件中,这可以在任何地方调用(不要将其钩接到 init 或其他操作,否则可能调用太晚)
<?php Routes::map('blog/:name', function($params){ $query = 'posts_per_page=3&post_type='.$params['name']; Routes::load('archive.php', null, $query, 200); }); Routes::map('blog/:name/page/:pg', function($params){ $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.$params['pg']; $params = array('thing' => 'foo', 'bar' => 'I dont even know'); Routes::load('archive.php', $params, $query); });
map
Routes::map($pattern, $callback)
用法
一个 functions.php
,我想在其中显示自定义分页内容
<?php Routes::map('info/:name/page/:pg', function($params){ //make a custom query based on incoming path and run it... $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.intval($params['pg']); //load up a template which will use that query Routes::load('archive.php', null, $query); });
参数
$pattern
(必需) 为路由设置一个匹配模式,默认情况下所有内容都作为字符串处理。任何以 :
开头的段都被处理为变量,例如
分页
page/:pagenum
编辑用户
my-users/:userid/edit
$callback
当模式与请求匹配时应触发的函数。回调函数接受一个参数,即传递到URL中的参数数组。
所以在这个例子中: 'info/:name/page/:pg'
,$params 将包含以下数据:
$data['name']
$data['pg']
... 你可以在回调函数中使用这些数据作为查询的一部分
load
Routes::load($php_file, $args, $query = null, $status_code = 200)
参数
$php_file
(必需) 要加载的PHP文件,根据我的经验,这通常是你的 archive.php 或通用列表页面(但不用担心,它可以 anything!)
$template_params
你想要发送到结果视图的任何数据。例如
<?php /* functions.php */ Routes::map('info/:name/page/:pg', function($params){ //make a custom query based on incoming path and run it... $query = 'posts_per_page=3&post_type='.$params['name'].'&paged='.intval($params['pg']); //load up a template which will use that query $params['my_title'] = 'This is my custom title'; Routes::load('archive.php', $params, $query, 200); });
<?php /* archive.php */ global $params; $context['wp_title'] = $params['my_title']; // "This is my custom title" /* the rest as normal... */ Timber::render('archive.twig', $context);
$query
你想要使用的查询,它可以接受字符串或数组,就像 Timber::get_posts
一样 — 使用标准 WP_Query 语法(或 WP_Query 对象)
$status_code
发送可选的状态码。默认为200表示“成功/OK”