How to sort list of custom posts to get view like a tree of posts under categories and their children’s categories?

ok, this is my working solution:

<?php

$args=array(
'post_type'                => 'biblioteka',
'child_of'                 => 0,
'parent'                   => '',
'orderby'                  => 'name',
'order'                    => 'ASC',
'hide_empty'               => 1,
'hierarchical'             => 1,
'exclude'                  => '',
'include'                  => '',
'number'                   => '',
'taxonomy'                 => 'kategoria-pozycji',
'pad_counts'               => false
);

$categories=get_categories($args);

foreach ( $categories as $category ) {

if ( $category->parent > 0 ) {
continue;   
}

echo '<h1 style="font-weight:bold">' . $category->name . '</h1>';

$querystr = "SELECT $wpdb->posts.*
          FROM $wpdb->posts, $wpdb->term_relationships, $wpdb->terms
          WHERE term_id = (" . $category->cat_ID . ")
          AND term_taxonomy_id = (" . $category->term_taxonomy_id . ")
          AND ID = object_id
          AND post_type="biblioteka"
          AND post_status="publish"
          ORDER BY post_date DESC";
$posts = $wpdb->get_results($querystr, OBJECT);

echo '<ul>';
foreach ( $posts as $post ) {
    setup_postdata($post);  

        echo '<li>'; the_title();   echo '</li>';

        }
echo '</ul>';

$categories2 = get_terms('kategoria-pozycji',array('parent' => $category->term_id , 'hide_empty'=> '0' ));

foreach ( $categories2 as $category ) {

echo '<h2>' . $category->name . '</h2>';

$posts = get_posts( array( 'kategoria-pozycji' => $category->name, 'post_type' => 'biblioteka' ) );  

echo '<ul>';
foreach($posts as $post) { 
    setup_postdata($post);  

        echo '<li>'; the_title();   echo '</li>';

        }
echo '</ul>';

}
}

?>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)