Wordpress自定义帖子类型的自定义category.php?

问题描述 投票:1回答:2

如何创建仅显示自定义帖子类型的帖子的category.php模板(例如category-testimonial.php)?

这是我创建自定义帖子类型的代码:

function testimonials_custom_init() {

    $labels = array(
        'name' => _x('Testimonials', 'post type general name'),
        'singular_name' => _x('Testimonial', 'post type singular name'),
        'add_new' => _x('Add New', 'testimonial'),
        'add_new_item' => __('Add New Testimonial'),
        'edit_item' => __('Edit Item'),
        'new_item' => __('New Testimonial'),
        'view_item' => __('View Testimonial'),
        'search_items' => __('Search Testimonials'),
        'not_found' =>  __('Nothing found'),
        'not_found_in_trash' => __('Nothing found in Trash'),
        'parent_item_colon' => ''
    );

    $args = array(
        'labels' => $labels,
        'public' => true,
        'publicly_queryable' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'show_in_nav_menus' => false,
        'query_var' => true,
        'rewrite' => array('slug','pages'),
        'capability_type' => 'post',
        'hierarchical' => false,
        'menu_position' => 5,
        'has_archive' => 'testimonials',
        'supports' => array('title','editor','thumbnail','excerpt',)
      );

    register_post_type( 'testimonials' , $args );
}
add_action( 'init', 'testimonials_custom_init' );
wordpress categories custom-post-type
2个回答
3
投票

听起来你混淆了分类法(标签和类别)和帖子类型(帖子,页面,自定义帖子类型)。您真正想要做的是为自定义帖子类型创建一个存档模板,如archive-custom_post_type.php

您还需要确保在创建自定义帖子类型时调用register_post_type()设置has_archive => 'custom_post_type'。然后,当您导航到http://yourdomain.com/custom_post_type时,您将转到自定义存档模板。

有关详细信息,请参阅WP关于register_post_typeTemplate Hierarchy的文档。


0
投票

这个问题可能很旧,但是,这可以帮助其他尝试获取自定义帖子类型的人显示自定义类别模板。假设您有一个名为“events”的自定义帖子类型。默认情况下,您希望例如拥有“category-events.php”并过滤仅与此自定义帖子类型相关联的类别。 Wordpress不会让你这样做(但也许)。

我的解决方法是首先在您的子主题中创建一个空白的category.php(或者您将删除该子主题文件中已有的任何内容并替换为下面的代码)。

然后粘贴该代码:

 if ( isset( $post_type ) && locate_template( 'category-' . $post_type . 
'.php' ) ) 

{

get_template_part( 'category', $post_type );

exit;

 }

而已。

现在,您需要创建实际的模板文件,如“category-events.php”。在该文件中,您可以使用get_header('your-custom-header')从archive.php或任何自定义模板中复制/粘贴代码; get_footer(“你定制头”);以及你需要的任何内容。当然,您需要的代码可以让您实际过滤该类别:

if( have_posts() ) {
    while( have_posts() ) {
      the_post(); ------ blah blah blah---your code
© www.soinside.com 2019 - 2024. All rights reserved.