Greetings Comrades programmers and colleagues, web developers, help solve the puzzle, please! There is such a code:

<?php $post_type = 'my-custom-post-type'; $taxonomies = get_object_taxonomies( array( 'post_type' => $post_type ) ); foreach( $taxonomies as $taxonomy ) : // Gets every "category" (term) in this taxonomy to get the respective posts $arg = array('hierarchical' => false, 'orderby' => 'title', 'order' => 'DESC'); $terms = get_terms("all", $arg); foreach( $terms as $term ) : ?> <?php $term = array_pop( $terms ); $parent_term = ( $term->parent ? get_term( $term->parent, 'all' ) : $term ); print_r($parent_term); if ( ! empty( $terms ) ) : echo '<strong>'.$parent_term->name.'</strong><br>'; endif; ?> <strong class="child_cat"><?php echo $term->name; ?></strong> <?php $args = array( 'post_type' => $post_type, 'orderby' => 'menu_order', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $term->slug, 'include_children' => false ) ) ); $posts = new WP_Query($args); if( $posts->have_posts() ): while( $posts->have_posts() ) : $posts->the_post(); ?> <a href="<?php the_permalink() ?>" class="child_url"><?php the_title(); ?></a> <?php endwhile; endif; ?> <?php endforeach; endforeach; ?> 

Which derives:

- Parent category name

--- Name of the child category

---- Post from this very category # 1

---- Post from this very category #N

Everything is fine, everything works, but I can not cope with duplicates of the parent category

see screenshot

Roughly speaking, I need a section to be displayed only once, or rather only a unique section is displayed, and if it is repeated, then we only output the first one. The screenshot noted a repetition of the red and blue arrow.

  • Found a great PHP function array_unique(); It looks like what I need! For example: $org = array('1', '2', '2', '3', '3', '4', '5', '6'); $new = array_unique($org); var_dump($org); $org = array('1', '2', '2', '3', '3', '4', '5', '6'); $new = array_unique($org); var_dump($org); displays only unique values ​​from the array, no repetitions! But now I have another question, how in my code to create an array that contains all the names of the parent category is it the same $ parent_term-> name !? - Andrew
  • Found a solution! As the saying goes: "All genius is simple." if ($parent_term->name !=$_parent_term) echo '<strong>'.$parent_term->name.'</strong><br>'; $_parent_term = $parent_term->name; - Andrew

0