How to list custom taxonomy categories?

I have a custom post type (CPT) which contains products, and a taxonomy that contains product terms. I need to display these terms on the page ‘Products’ and when clicked on a certain term, it needs to display the products which belong to the term.

By the way, when I click ‘view’ on a certain term, it only displays one product’s title. I created the CPT and taxonomy using the CPT UI plugin.

Here is my page-products.php template file code (which lists all the products) :

<?php
/* Template Name: Products
*/
?>

 <?php get_header('header.php') ?>

 <!--Opening container or wrap outside of the loop-->
 <div class="container my-container">
 <!--start the loop-->
   <?php
   $args=array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => 10,
);

$the_query = null;
$the_query = new WP_Query($args);

if( $the_query->have_posts() ) {

$i = 0;
while ($the_query->have_posts()) : $the_query->the_post();

if($i % 3 == 0) { ?>

<div class="row">

<?php
}
?>

<div class="col-md-4">
  <div class="my-inner">
    <?php the_post_thumbnail(); ?>
    <div class="title"><a href="https://wordpress.stackexchange.com/questions/287501/<?php the_permalink(); ?>"><?php 
the_title(); ?></a></div>
    <?php the_excerpt(); ?>
  </div>
</div>

  <?php $i++;
  if($i != 0 && $i % 3 == 0) { ?>
    </div><!--/.row-->
    <div class="clearfix">fgfd</div>

  <?php
   } ?>

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

1 Answer
1

To get a list of your custom taxonomies, you can use the get_terms() function to create a loop:

// Get the taxonomy's terms
$terms = get_terms(
    array(
        'taxonomy'   => 'your-taxonomy',
        'hide_empty' => false,
    )
);

// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
    // Run a loop and print them all
    foreach ( $terms as $term ) { ?>
        <a href="https://wordpress.stackexchange.com/questions/287501/<?php echo esc_url( get_term_link( $term ) ) ?>">
            <?php echo $term->name; ?>
        </a><?php
    }
} 

Leave a Comment