2

I am trying to query a list with all Categories, Subcategories and Posts of a custom post type.

e.g.:

Maincat1
  -Subcat1
     -Post1
     -Post2
  -Subcat2
  -Subcat3
Maincat2
  -Subcat3
     -Post3
Maincat3
  -Post4

I'm getting mad trying to accomplish that. I tried out so many things that I found on the web but I can't figure out how to get it to work.

What I have so far (working), All Categories + Subcategories but i don't get it how to query the posts from the Categories / Subcategories.

<?php

$orderby      = 'name';
$show_count   = 1;      // 1 for yes, 0 for no
$pad_counts   = 1;      // 1 for yes, 0 for no
$hierarchical = 1;      // 1 for yes, 0 for no
$title        = '';
$empty        = 0;

$args = array(
  'taxonomy'     => 'kategorie',
  'orderby'      => $orderby,
  'show_count'   => $show_count,
  'pad_counts'   => $pad_counts,
  'hierarchical' => $hierarchical,
  'title_li'     => $title,
  'hide_empty'   => $empty
);

?>
<?php

$parent_cat_arg = array('hide_empty' => false, 'parent' => 0 );
$parent_cat = get_terms('kategorie',$parent_cat_arg);//category name

foreach ($parent_cat as $catVal) {

    echo '<h3>'.$catVal->name.'</h3>'; //Parent Category

$args = array('post_type' => 'Dokumente',
        'tax_query' => array(
            array(
                'taxonomy' => 'kategorie',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );


$my_query = new WP_Query( $args );

if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <ul><li><a href="#" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><li></ul><?php
    endwhile;
}

wp_reset_query();


    $child_arg = array( 'hide_empty' => false, 'parent' => $catVal->term_id );
    $child_cat = get_terms( 'kategorie', $child_arg );

    echo '<ul>';
        foreach( $child_cat as $child_term ) { 
            echo '<li>'.$child_term->name . '</li>'; //Child Category



$my_query = new WP_Query( $args );

if( $my_query->have_posts() ) {
    while ($my_query->have_posts()) : $my_query->the_post(); ?>
        <ul><li><a href="#" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a><li></ul><?php            
    endwhile;
}

wp_reset_query();
        }
    echo '</ul></li>';

}
?>
</div>
<?php

}

add_shortcode('kategorien', 'get_mylist' );

I also have the code to query the posts (at least i think it works) - but i don't know how to combine them.

$custom_terms = get_terms('kategorie');

foreach($custom_terms as $custom_term) {
wp_reset_query();

$args_slugs = array('post_type' => 'Dokumente',
        'tax_query' => array(
            array(
                'taxonomy' => 'kategorie',
                'field' => 'slug',
                'terms' => $custom_term->slug,
            ),
        ),
     );


     $loop = new WP_Query($args_slugs);
     if($loop->have_posts()) {
        while($loop->have_posts()) : $loop->the_post();
            echo '<ul><li><a href="'.get_permalink().'">'.get_the_title().'</a></li></ul><br>';
        endwhile;
     }
}

I really hope someone can help me... And yes I already used the search and found similar questions but none of the answers worked for me.

Best, NixXxon

  • What I understand from your question is, that you are trying to list all posts belongs to a custom post type using categories/subcategories defiend for post type. Is it like that? – BlueSuiter Sep 30 '17 at 17:33
  • Yes, sorry - i'm not a native english speaker :) - I'll try to visualize it in my question. – Niko Sep 30 '17 at 17:50
  • There is an error in your written query, you passed variable named $custom_term->slug however there is no variable defiend with this name. – BlueSuiter Sep 30 '17 at 19:02
  • to be honest, i do not completly understand the code. It's not written by me. I found it in another question @ stackexchange - but it seems to work - when i run it, it returns all posts of the category named "kategorie". But if a post is in more then one category it get's returned more then once (i guess thats ok when combined with the code above which return the categories and subcategories) - i already turned off my computer but i will check tomorrow if this variable is really necassary... – Niko Sep 30 '17 at 20:21
  • Tried to remove the line but then i doesn't work anymore; Isn't it defines here "foreach($custom_terms as $custom_term)"? – Niko Oct 1 '17 at 6:56
1

@niko Please, find your required code, it will give you exact output you were seeking for. I think you were doing all right except in the final output you were missing the right structure.

Also, I recommand not to assign posts to the parent category as this structure not support that. However, I think with minor tweaks in following that can also be acheived.

<?php   
    $taxonomy = 'testimonial-category';
    $postType = 'testimonial';
    $terms = get_terms(['taxonomy' => $taxonomy, 'orderby' => 'term_id', 'parent' => 0, 'hide_empty' => false]);
?>
<div class="">
<?php
    foreach($terms as $term){
        echo '<h3>' . $term->name . '</h3>';
        $childTerms = get_terms(['taxonomy' => $taxonomy, 'orderby' => 'term_id', 'parent' => $term->term_id, 'hide_empty' => false]);

        foreach($childTerms as $childTerm)
        {
            $posts = get_posts(array('post_status' =>'publish','post_type' => $postType,
                    array(
                        'taxonomy' => $taxonomy,
                        'field' => 'term_id',
                        'terms' => $childTerm->term_id,
                    ),));
            ?>
            <div class="add-accordion">
                <h3><?php echo $childTerm->name ?></h3>
                <div class="add-accordion">
                    <?php foreach($posts as $post){ ?>
                        <h3><?php echo $post->post_title ?></h3>
                        <div class="">
                            <?php echo get_the_content($post->ID) ?>
                        </div>
                    <?php } ?>
                </div>
            </div>
            <?php
        }
    }
?>
</div>
<script>
    jQuery(function(){
        jQuery('.add-accordion').accordion({
            collapsible: true,
            heightStyle: "content",
            active: false,
            animate: 500,
            icons: false
        });
    });
</script>
<?php wp_enqueue_script('jquery-ui-accordion'); ?>
  • THANK YOU very much - it's for sure a step in the right direction but still not really working. see: goo.gl/bGj2S6 I only changed the "content echo" to "list with permalinks". I'm sure the posts you can see under each categorie are not in all those categories. – Niko Oct 13 '17 at 17:17
  • @Niko Please look into the code again. I have made some logical updates. – BlueSuiter Oct 14 '17 at 7:27
0

To display a list of all your categories, subcategories and posts inside each subcategory, use this code. Make sure to change your the arguments with your own taxonomy and post type and read the comments in the code for more clarification:

function ow_categories_with_subcategories_and_posts( $taxonomy, $post_type ) {

    // Get the top categories that belong to the provided taxonomy (the ones without parent)
    $categories = get_terms( 
        array(
            'taxonomy'   => $taxonomy,
            'parent'     => 0, // <-- No Parent
            'orderby'    => 'term_id',
            'hide_empty' => true // <!-- change to false to also display empty ones
        )
    );
    ?>
    <div>
        <?php
        // Iterate through all categories to display each individual category
        foreach ( $categories as $category ) {

            $cat_name = $category->name;
            $cat_id   = $category->term_id;
            $cat_slug = $category->slug;

            // Display the name of each individual category
            echo '<h3>Category: ' . $cat_name . ' - ID: ' . $cat_id . ' - Slug: ' . $cat_slug  . '</h3>'; 


            // Get all the subcategories that belong to the current category
            $subcategories = get_terms(
                array(
                    'taxonomy'   => $taxonomy,
                    'parent'     => $cat_id, // <-- The parent is the current category
                    'orderby'    => 'term_id',
                    'hide_empty' => true
                )
            );
            ?>
            <div>
                <?php
                // Iterate through all subcategories to display each individual subcategory
                foreach ( $subcategories as $subcategory ) {

                    $subcat_name = $subcategory->name;
                    $subcat_id   = $subcategory->term_id;
                    $subcat_slug = $subcategory->slug;

                    // Display the name of each individual subcategory with ID and Slug
                    echo '<h4>Subcategory: ' . $subcat_name . ' - ID: ' . $subcat_id . ' - Slug: ' . $subcat_slug  . '</h4>';

                    // Get all posts that belong to this specific subcategory
                    $posts = new WP_Query(
                        array(
                            'post_type'      => $post_type,
                            'posts_per_page' => -1, // <-- Show all posts
                            'hide_empty'     => true,
                            'order'          => 'ASC',
                            'tax_query'      => array(
                                array(
                                    'taxonomy' => $taxonomy,
                                    'terms'    => $subcat_id,
                                    'field'    => 'id'
                                )
                            )
                        )
                    );

                    // If there are posts available within this subcategory
                    if ( $posts->have_posts() ):
                        ?>
                        <div>
                            <?php

                            // As long as there are posts to show
                            while ( $posts->have_posts() ): $posts->the_post();

                                //Show the title of each post with the Post ID
                                ?>
                                <p>Post: <?php the_title(); ?> - ID: <?php the_ID(); ?></p>
                                <?php

                            endwhile;
                            ?>
                        </div>
                        <?php
                    else:
                        echo 'No posts found';
                    endif;

                    wp_reset_query();
                }
                ?>
            </div>
            <?php
        }
        ?>
    </div>
    <?php
}
ow_categories_with_subcategories_and_posts( 'name_of_your_taxonomy', 'name_of_your_post_type' );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.