0

I'm not sure if this is possible but I'm trying to get my taxonomy.php file to work the same for all 10 of my custom taxonomies. The code below works exactly as I need it to (ie: when at a url ending ../inventory/yearmade/2017/ all the posts with the yearmade taxonomy term of 2017 are looped and output (or any year entered at the end of the url).

But I currently have to make 10 different taxonomy-[taxonomy].php files, each with the code change of just a different string in the taxonomy => '___' (yearmade, make, model, length, beam, engine, size, horsepower, drive, trailer).

I was able to use 'terms' => '$queried_object->slug' (line 8) for dynamic loading of the term. Is there a way to do the same for the taxonomy?

I've tried the same on line 6: 'taxonomy' => '$queried_object->slug' but it does not work.

<?php
  $queried_object = get_queried_object();
  $query = new WP_Query( array(
    'post_type' => "inventory",
    'tax_query' => array(
      array(
        'taxonomy' => "yearmade',
        'field' => "slug",
        'terms' => "$queried_object->slug",
      )
    )
  ) );
  while ( $query->have_posts() ) : $query->the_post(); ?>

    <div>
      <h2><?php the_title(); ?></h2>
      <ul>
        <li>Year: <?php the_terms( $post->ID, 'yearmade'); ?>
        <li>Make: <?php the_terms( $post->ID, 'make'); ?>
        <li>Model: <?php the_terms( $post->ID, 'model'); ?>
        <li>Length: <?php the_terms( $post->ID, 'length'); ?>
        <li>Beam: <?php the_terms( $post->ID, 'beam'); ?>
        <li>Engine: <?php the_terms( $post->ID, 'engine'); ?>
        <li>Size: <?php the_terms( $post->ID, 'size'); ?>
        <li>Horsepower: <?php the_terms( $post->ID, 'horsepower'); ?>
        <li>Drive: <?php the_terms( $post->ID, 'drive'); ?>
        <li>Trailer: <?php the_terms( $post->ID, 'trailer'); ?>
      </ul>
    </div>

  <?php endwhile; ?>
<?php wp_reset_query(); ?>
3

In a taxonomy template, the queried object is an instance of WP_Term, one of whose fields will be the taxonomy the term comes from.

So, you can start your taxonomy.php as follows:

$queried_object = get_queried_object () ;
$args = array (
    'post_type' => 'inventory',
    'tax_query' => array (
        array (
            'taxonomy' => $queried_object->taxonomy,
            'field' => 'slug',
            'terms' => $queried_object->slug,
            ),
        ),
    ) ;
$query = new WP_Query ($args) ;
  • Hmmm...I had tried 'taxonomy' => $queried_object->taxonomy in my code but it did not work. I see your code is a little different overall than mine...but I'm not sure the exact difference and why :( But it works! And now I have a bit more information to research. Thank you. – codeview Mar 12 '17 at 0:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.