CyberJunkie
CyberJunkie

Reputation: 22674

Wordpress same archive template for custom post type and taxonomy

I created a custom taxonomy for tags

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' ),
  ));
}

and connected it to my custom post type

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

The custom post type uses archive-video.php as the archive template. Is it possible to use the same archive template for the custom taxonomy? Without duplicating the file and renaming it.

Upvotes: 1

Views: 1137

Answers (2)

Pieter Goosen
Pieter Goosen

Reputation: 9941

You can make use of the template_include filter to set the template you need for a specific condition

You can try something like this

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 );

Upvotes: 4

Nathan Dawson
Nathan Dawson

Reputation: 19308

I'd create the taxonomy file and have it load the archive file. This avoids having two copies of the same file which need to be kept in sync. WooCommerce uses the same approach for product categories and tags.

Create taxonomy-topics.php and add the following code:

<?php

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

Upvotes: 4

Related Questions