humanmade / hm-rewrite
HM_Rewrite 是 WordPress WP Rewrite 系统的包装器。http://hmn.md/wordpress-rewrite-rules-hm-core-style/
Requires
- php: >=5.2
- composer/installers: ~1.0
This package is auto-updated.
Last update: 2024-08-26 18:22:08 UTC
README
HM_Rewrite
和 HM_Rewrite_Rule
是 WordPress rewrite / wp_query 系统的包装器。
HM_Rewrite 和相关函数/类的目标是让添加新路由点(如动态页面、post_type_archive
等)变得非常简单。它基本上将几个任务封装成一套优秀的 API。几乎所有设置新路由页面所需的操作都可以一次完成,主要依赖 PHP Closures。它本质上封装了添加到 rewrite_rules
,将模板文件添加到 template_redirect
,wp_title
钩子,body_class
钩子,parse_query
钩子等。还提供了一些方便的回调函数。每个重写规则都是一个 HM_Rewrite_Rule
实例。在这里,你可以添加正则表达式/ wp_query
变量以及“页面”的任何其他选项。例如,添加查询变量的回调函数到 parse_request
,或添加到 * body_class
的回调函数。还有一个用于一次性调用所有这些的包装函数 hm_add_rewrite_rule()
。通常推荐使用 hm_add_rewrite_rule()
接口,对于更复杂的功能(以及附加到其他重写规则)可以与底层对象交互。(简单用例示例)
hm_add_rewrite_rule( array( 'regex' => '^users/([^/]+)/?', 'query' => 'author_name=$matches[1]', 'template' => 'user-archive.php', 'body_class_callback' => function( $classes ) { $classes[] = 'user-archive'; $classes[] = 'user-' . get_query_var( 'author_name' ); return $classes; }, 'title_callback' => function( $title, $seperator ) { return get_query_var( 'author_name' ) . ' ' . $seperator . ' ' . $title; } ) );
使用更多回调的更复杂示例
hm_add_rewrite_rule( array( 'regex' => '^reviews/([^/]+)/?', // a review category page 'query' => 'review_category=$matches[1]', 'template' => 'review-category.php', 'request_callback' => function( WP $wp ) { // if the review category is "laptops" then only show items in draft if ( $wp->query_vars['review_category'] == 'laptops' ) $wp->query_vars['post_status'] = 'draft'; }, 'query_callback' => function( WP_Query $query ) { //overwrite is_home because WordPress gets it wrong here $query->is_home = false; }, 'body_class_callback' => function( $classes ) { $classes[] = get_query_var( 'review_category' ); return $classes; }, 'title_callback' => function( $title, $seperator ) { return review_category . ' ' . $seperator . ' ' . $title; }, 'rewrite_tests_callback' => function() { return array( 'Review Category' => array( '/reviews/foo/', '/reviews/bar/', ), ); } ) );
贡献指南
请参阅https://github.com/humanmade/hm-rewrite/blob/master/CONTRIBUTING.md