Search code examples
phpwordpressarchivetaxonomycustom-taxonomy

Using the taxonomy-tax_slug.php template to create an archive for all taxonomy terms


I have created a Custom Post Type, yacht, with a taxonomy of yacht_types (which includes Catamaran, Motor Yacht and Sailing).

I want each type to have its own archive by using the taxonomy-yacht_type.php, not the taxonomy-yacht_type-catamaran, motor-yacht etc..

I've been researching and trying stuff out for 2 days now and I can't seem to move forward so I suppose it's a lack of knowledge now. The code below is the one I would've used in the "taxonomy-yacht_type-catamaran.php" case.

<?php
    $args['tax_query'] = array(
        array(
            'taxonomy' => 'yacht_type',
            'field' => 'term_id',
            'terms' => 10,
        )
    );
    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
        while ($my_query->have_posts()) : $my_query->the_post(); 
            $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>

                ** html for each post repeat goes here **

        <?php endwhile; 
    }

    wp_reset_query();
?> 

Is there a way to somehow automatically get the tax id without having to manually input it (as seen in line 6 of my code)? Because that means I'm gonna have to create and manage 3 different files that would technically do the exact same job as the one I want to..


Solution

  • I would use a query string for something like this, it works well unless you're fussy about the urls. Some people don't like ?= in their url http://www.example.com/yacht-tax-page?type=catamaran

    Then you can read the value in the $_GET array

    Sorry just re-read the question it's actually something completely different to what I thought it was.

    You can just use the taxonomy.php or the taxonomy-yacht_type.php with a standard loop. Try the code below in your taxonomy template file.

    <?php if ( have_posts() ) : while ( have_posts() ) : the_post();
         $feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>
    
         ** html for each post repeat goes here **
    
    <?php endwhile; else: ?>
        <p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
    <?php endif; ?>