【问题标题】:Wordpress same archive template for custom post type and taxonomy用于自定义帖子类型和分类的 Wordpress 相同存档模板
【发布时间】:2015-02-12 21:36:13
【问题描述】:

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

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 作为存档模板。是否可以为自定义分类法使用相同的存档模板?无需复制文件并重命名它。

【问题讨论】:

  • 谢谢。该功能将不起作用,因为我没有使用archives.php。我正在使用一个名为 archive-video.php 的自定义存档(也在子目录中)

标签: php wordpress custom-post-type taxonomy


【解决方案1】:

您可以使用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 );

【讨论】:

  • archive-video.php 之后有一个额外的空间会破坏您的示例。我把头发拉了一个小时,但我无法编辑它,因为编辑少于 6 个字符。
  • @StephenSmith 感谢您指出这一点,已更正:-)
【解决方案2】:

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

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

<?php

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 2022-07-20
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多