R
R
ratyk2019-04-23 18:27:36
Taxonomy
ratyk, 2019-04-23 18:27:36

How to display a subcategory of a custom taxonomy category?

In general, I need to display the subcategories of the first level of the current category of the custom taxonomy, but not in the form of a sheet, but in some controlled layout, where I can place it anywhere, and if there are no subcategories, then display the posts already tied to it. I searched through a lot of content, but could not find what I was looking for. Help me please.
How I imagine this code:
if (if there is a subcategory) {
output subcategories;
}
else {
if ( have_posts() ) : while (have_posts()) : the_post(); etc.
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan Hasanli, 2019-04-23
@ratyk

Hello!
I had a similar problem before...
Here is a simple skeleton of what you want:

<?php 
$currentTerm = get_queried_object();
$children = get_term_children($currentTerm -> term_id, 'MY_TAXONOMY');
if($children): ?>
  <?php 
        $args = array(
          'taxonomy' => 'MY_TAXONOMY',
          'hide_empty' => false,
          'depth' => 1,
          'child_of' => get_queried_object()->term_id
        );
        $terms = get_terms( $args );
        $count = 1;
  ?>

  <?php foreach ($terms as $term): ?>

    <a href="<?php echo $term->slug ?>"><?php echo $term->name ?></a>

  <?php endforeach; ?>

  <?php else : ?>

    <?php 
    	$postCount = 1;
      $args = array(
        'posts_per_page' => -1,
        'MY_TAXONOMY' => $currentTerm->name
      );

      $query = new WP_Query( $args );
      if ($query->have_posts()) : 
        while ($query->have_posts()) : $query->the_post(); ?>
            <a href="<?php the_permalink() ?>">
                  <div class="title"><?php the_title(); ?></div>
            </a>

      <?php endwhile; ?>
      <?php endif; ?>

<?php endif;?>

MY_TAXONOMY - my custom taxonomy. You can change to your own version or use the default category taxonomy.
In the first part, we get get_queried_object();and see if there are child categories, if there are, then display them, and if not (the else branch), then display the posts

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question