您必须添加一些新的重写规则,谢天谢地,WordPress通过几个函数调用使它变得相当简单。
// use the init action to modify rewrite rules
add_action( \'init\', function() {
global $wp_rewrite;
// add rewrite tag for the post type
// - %posttype% is a new tag that will be replaced with the regex in the actual query
// - the regex will extract the post_type name from the URL and use it in the query
add_rewrite_tag( \'%posttype%\', \'([^/]+)\', \'post_type=\' );
// create the new permastruct by combining the post type & taxonomy permastructs
// - custom taxonomies and post types are added to the extra_permastructs array in WP_Rewrite
// - change \'category\' to desired taxonomy
// - output will be \'%posttype%/category/%category%\'
$types_and_cats_permastruct = \'%posttype%\' . $wp_rewrite->get_extra_permastruct( \'category\' );
// add the permastruct for post type & taxonomy
add_permastruct( \'post_type_and_category\', $types_and_cats_permastruct, array(
\'with_front\' => true, // - with_front (bool) - Should the structure be prepended with WP_Rewrite::$front? Default is true.
\'ep_mask\' => EP_ALL_ARCHIVES, // - ep_mask (int) - Endpoint mask defining what endpoints are added to the structure. Default is EP_NONE.
\'paged\' => true, // - paged (bool) - Should archive pagination rules be added for the structure? Default is true.
\'feed\' => true, // - feed (bool) - Should feed rewrite rules be added for the structure? Default is true.
\'forcomments\' => false, // - forcomments (bool) - Should the feed rules be a query for a comments feed? Default is false.
\'walk_dirs\' => false, // - walk_dirs (bool) - Should the \'directories\' making up the structure be walked over and rewrite
// rules built for each in turn? Default is true.
\'endpoints\' => true // - endpoints (bool) - Should endpoints be applied to the generated rewrite rules? Default is true.
) );
} );
为了解释我在上面所做的事情:
添加重写标记add_rewrite_tag()
因此,当您将自定义帖子类型名称放入URL(例如/events/location/uk/)时,它将被正则表达式识别,并且生成的查询WP运行将包含post_type=events
创建一个新的permastruct来生成使用我们刚才添加的标记和现有分类法permastruct的规则,在您的情况下,这将是位置,所以/event/location/uk
将展示英国活动和/business/location/uk
将向英国企业展示add_permastruct()
因此,无论何时刷新永久链接,WP都会生成新的重写规则。在第三个参数中walk_dirs
设置为false,因为您将获得一些不受欢迎的具有存档的侵略性重写规则/%posttype%/category/
和/%posttype%/
获取链接-如果要使用the_terms()
要为仅显示原始帖子类型的业务或事件输出位置链接,您必须过滤URL或编写自定义函数以输出URL以匹配您的permastruct。如果您不希望存档同时列出事件和业务,则最好使用两种不同的分类法,因为您可以更容易地判断某个术语中是否有帖子,例如,在生成链接时以及决定是否输出指向空存档的链接。那样的话@richard-howarth\'s answer is correct