C
C
Chingiz Huseynov2021-11-26 20:06:55
WordPress
Chingiz Huseynov, 2021-11-26 20:06:55

How to display a list of categories (with thumbnails, etc.) and nested drop-down lists of their subcategories?

61a1185fb827e604402644.jpegHello. I'm trying to implement a list of categories (parents) with a dropdown list of subcategories under each of the categories. Since I myself am new to php, I have already asked for help with this question and I was prompted, however, the code is raw and cycles through everything. I would like to get the html structure by type:

<ul>
  <li>Родитель</li>
  <li>Родитель</li>
  <li>Родитель      
    <ul>
       <li>Ребенок</li>
    </ul>
  </li>
</ul>


Here's what I have at the moment, the function is recursive and rather not very readable.

/**
 * Пользовательская рекурсивная функция вывода категорий 
 * Для вывода шорткода [product_categories_dropdown]
 * 
 */

add_shortcode('product_categories_dropdown', 'first_child_terms_list');

function first_child_terms_list()
{
  // Запрашиваем дочерние элементы верхнего уровня всех термина
  $terms = get_terms([
    'taxonomy'    => 'product_cat',
    'orderby'     => 'id', // здесь по какому полю сортировать
    'hide_empty'  => true, // скрывать категории без товаров или нет
  ]);

  // Если возникла ошибка запроса или терминов нет - прерываем выполнение функции
  if (is_wp_error($terms) || !$terms) {
    return;
  }

  echo '<div class="categories-dropdown">';
    recursive_show_terms($terms, 0);
  echo '</div>';
}

function recursive_show_terms($terms, $parent_id = 0, $deep = -1)
{
  if (0 == $deep) {
    return;
  }

  foreach ($terms as $term) {

    if ($term->parent !== $parent_id) {
      continue;
    }
    if ($term->parent == 0) {
      $thumbnail_id = get_term_meta($term->term_id, 'thumbnail_id', true);
    }
    if ($term->parent > 0) {
      $child_class_ul = 'categories-dropdown__wrapper_child';
      $child_class_li = 'categories-dropdown__items_child';
    }
?>

    <ul class="categories-dropdown__wrapper <?php echo !empty($child_class_ul) ? $child_class_ul : ''; ?>">
      
        <?php

        printf(
          '<li class="categories-dropdown__items %s">
            <a class="categories-dropdown__links" href="%s">
            %s
              <h4 class="categories-dropdown__title">%s</h4>
            </a>
          </li>',
          !empty($child_class_li) ? $child_class_li : '',
          esc_url(get_term_link($term)),
          !empty($thumbnail_id) ? '<div class="categories-dropdown__img" ><img src="' . wp_get_attachment_url($thumbnail_id) . '" loading="lazy"></div>' : '',
          esc_html($term->name)
        )
        ?>
      

      <?php recursive_show_terms($terms, $term->term_id, $deep - 1); ?>

    </ul>

<?php
  }
}

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question