Wordpress用于自定义帖子类型和分类的相同存档模板

时间:2014-12-14 19:15:18

标签: php wordpress custom-post-type taxonomy

我为标签创建了自定义分类

function create_topics_nonhierarchical_taxonomy() {

  // Labels part for the GUI

  $labels = array(
    'name' => _x( 'Topics', 'taxonomy general name' ),
    'singular_name' => _x( 'Topic', 'taxonomy singular name' ),
    'search_items' =>  __( 'Search Topics' ),
    'popular_items' => __( 'Popular Topics' ),
    'all_items' => __( 'All Topics' ),
    'parent_item' => null,
    'parent_item_colon' => null,
    'edit_item' => __( 'Edit Topic' ), 
    'update_item' => __( 'Update Topic' ),
    'add_new_item' => __( 'Add New Topic' ),
    'new_item_name' => __( 'New Topic Name' ),
    'separate_items_with_commas' => __( 'Separate topics with commas' ),
    'add_or_remove_items' => __( 'Add or remove topics' ),
    'choose_from_most_used' => __( 'Choose from the most used topics' ),
    'menu_name' => __( 'Topics' )
  ); 

  // Now register the non-hierarchical taxonomy like tag

  register_taxonomy('topics','post',array(
    'hierarchical' => false,
    'labels' => $labels,
    'show_ui' => true,
    'show_admin_column' => true,
    'update_count_callback' => '_update_post_term_count',
    'query_var' => true,
    'show_in_nav_menus' => true,
    'rewrite' => array( 'slug' => 'topic' ),
  ));
}

并将其连接到我的自定义帖子类型

register_post_type( 'video', array(
   ...
   'taxonomies' => array( 'topics' ),
   ...
) );

自定义帖子类型使用archive-video.php作为存档模板。是否可以使用相同的归档模板进行自定义分类?不重复文件并重命名。

2 个答案:

答案 0 :(得分:4)

我会创建分类文件并让它加载存档文件。这样可以避免同一个文件的两个副本需要保持同步。 WooCommerce对产品类别和标签使用相同的方法。

创建taxonomy-topics.php并添加以下代码:

<?php

// Find and load the archive template.
locate_template( 'archive-video.php', true );

答案 1 :(得分:3)

您可以使用template_include过滤器来设置特定条件所需的模板

您可以尝试这样的事情

add_filter( 'template_include', function ( $template ) {

    if ( is_tax( 'topics' ) ) {
    $new_template = locate_template( array( 'archive-video.php' ) );
        if ( '' != $new_template ) {
            return $new_template ;
        }
    }
    return $template;

}, PHP_INT_MAX, 2 );
相关问题