Někdy se vyskytne zajímavý usecase vypsat strukturu kategorií a jejich příspěvků včetně hierarchie.
K tomu můžete použít následující kod, který si račte jak libo upravit.
- vypíše rekurzivně všechny termy dané taxonomie
- taxonomii “my-awesome-taxonomy” a post type “my-awesome-post-type” je třeba vyměnit za vaše
- pomocí shortcode [files_hierarchy] to vypíšete libovolně na stránce
function display_term_hierarchy_with_posts($taxonomy, $parent = 0, $level = 0)
{
$args = array(
'taxonomy' => $taxonomy,
'parent' => $parent,
'hide_empty' => false,
);
$terms = get_terms($args);
if (!empty($terms) && !is_wp_error($terms)) {
echo '<ul>';
foreach ($terms as $term) {
if ($parent == 0) {
echo '<li style="padding-top: 32px; list-style-type: none; font-size: "><h3>' . $term->name . '</h3>';
} else {
echo '<li style="padding-top: 32px; list-style-type: none; font-size: "><b>' . $term->name . '</b>';
}
$posts = get_posts(array(
'post_type' => 'my-awesome-post-type',
'post_status' => 'publish',
'posts_per_page' => 1000,
'orderby' => 'date',
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'term_id',
'terms' => $term->term_id,
'include_children' => false,
),
),
));
if (!empty($posts)) {
echo '<ul>';
foreach ($posts as $post) {
$file_path = get_post_field('file_url', $post->ID);
echo '<li>🗎 <a target="_blank" style="text-decoration: underline" href="' . $file_path . '">' . get_the_title($post->ID) . '</a></li>';
}
echo '</ul>';
}
display_term_hierarchy_with_posts($taxonomy, $term->term_id, $level + 1);
echo '</li>';
}
echo '</ul>';
}
}
function display_recursive_hierarchy()
{
$taxonomy = 'my-awesome-taxonomy';
display_term_hierarchy_with_posts($taxonomy);
}
add_shortcode('recursive_hierarchy', 'display_recursive_hierarchy');

