Novinka: Vizuální editor pro éru AI webů. Poslední dílek skládačky, když chcete upravovat web a ne psát e-maily. www.directedit.dev

💬

Zobrazení hierarchie s příspěvky

Rekurzivní výpis kategorií i s příspěvky

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>&#128462; <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');

Líbil se vám článek? Pošlete ho dál:

Jitka Klingenbergová

Jitka Klingenbergová

Absolventka ČVUT FIT oboru Informatika | Programátorka | Webová vývojářka, konzultantka a mentorka
tvorime@vyladeny-web.cz

Vaše komentáře

Zanechte první komentář

Zpět k tipům

Pravidelná dávka užitečných tipů až do schránky