这与问题不同:How to display categories of my Custom Post Type?
我有一个自定义的帖子类型-播客。我添加了分类法“category”,因为我希望我的“podcast”与我的帖子共享“category”分类法。我有一个归档页面(archive podcasts.php),它在url/podcasts/处显示播客,但它shows all the categories. 我想在中显示我的播客a single category at a time, 比如在mysite。com/podcasts/category/mycategory/
或者更好:mysite。com/category/mycategory/podcasts/
理想情况下,它将使用我现有的存档播客。php模板。
以下是我的自定义帖子类型创建:
function podcast_post_type() {
// Set UI labels for Podcast post Type
$labels = array(
//redacted my labels because they aren\'t important here.
);
// Set other options for Podcast post Type
$args = array(
\'label\' => __( \'podcasts\', \'understrap\' ),
\'description\' => __( \'Podcasts\', \'understrap\' ),
\'labels\' => $labels,
// Features this CPT supports in Post Editor
\'supports\' => array( \'title\', \'editor\', \'excerpt\', \'author\', \'thumbnail\', \'comments\', \'revisions\', \'custom-fields\', ),
// You can associate this CPT with a taxonomy or custom taxonomy.
\'taxonomies\' => array( \'category\' ),
/* A hierarchical CPT is like Pages and can have
* Parent and child items. A non-hierarchical CPT
* is like Posts.
*/
\'hierarchical\' => false,
\'public\' => true,
\'show_ui\' => true,
\'show_in_menu\' => true,
\'show_in_nav_menus\' => true,
\'show_in_admin_bar\' => true,
\'menu_position\' => 5,
\'can_export\' => true,
\'has_archive\' => true,
\'exclude_from_search\' => false,
\'publicly_queryable\' => true,
\'capability_type\' => \'post\',
);
// Registering your Podcast post Type
register_post_type( \'podcasts\', $args );
}
以下代码似乎很有希望,但不起作用:
add_action(\'init\', \'category_cpt_rewrites\');
function category_cpt_rewrites() {
$custom_post_types = array(\'podcasts\'); //some example post types
foreach ( $custom_post_types as $post_type ) {
$rule = \'^\' . $post_type . \'/category/(.+?)/?$\';
$rewrite = \'index.php?post_type=\' . $post_type . \'&category_name=$matches[1]\';
add_rewrite_rule($rule,$rewrite,\'top\');
}
}
实际上,我有点期待这会自动工作——通过在我的帖子类型中添加“类别”分类法,我认为Wordpress会有一个url,我可以在那里访问我的播客类别。
我为此浪费了很多时间,看起来应该很简单——感谢您的帮助!