Search code examples
wordpresscustom-post-typetaxonomy

wordpress override template hierarchy


I have a custom post type "accommodation" and a custom taxonomy "tax_destination". When i put this url:

/?post_type=accommodation&tax_destination=granada

the template rendered is: taxonomy-tax_destination.php

Is it possible to use archive-accommodation.php instead?

What I want is to show the accommodation's list for that taxonomy using the archive template.


Solution

  • WordPress has a handy filter called template_include that allows you to override which template files are included on a particular request. You can combine that with a check using is_tax(). The $term argument is optional, but since you included one I'm going to include it so it only works for the granada term:

    add_filter( 'template_include', 'accommodation_template', 99 );
    function accommodation_template( $template ) {
        if( is_tax( 'tax_destination', 'granada' ) ){
            $new_template = locate_template( array( 'archive-accommodation.php' ) );
            if( !empty( $new_template ) ){
                return $new_template;
            }
        }
    
        return $template;
    }
    

    If you put this in your functions.php file, it will determine if the current request is for the term granada in the taxonomy tax_destination, and return the archive-accommodation.php template.

    Note: If you reuse those tax/terms on other post types, you may need to include is_post_type_archive( 'accommodation' ) or get_post_type() == 'accommodation' to your if statement as well.