Reputation: 21
I have this code that works fine but the problem is with the ordering of the displayed data. Now it is little disorder and posts are duplicated when you check subcategory position. What can I do to display a tree of categories with posts included in each category and subcategory, for example :
<h1>Prime Category 1</h1>
<ul>
<li>Post 1</li>
<li>Post 2</li>
<li>...</li>
</ul>
<h2>Sub Category 1</h2>
<ul>
<li>Post 1</li>
<li> Post 2</li>
<li>...</li>
</ul>
<h2>Sub Category 2</h2>
<ul>
<li>Post 1</li>
<li> ...</li>
</ul>
<h1>Prime Category 2</h1>
<h2>Sub Category</h2>
<ul>
<li>Post 1</li>
<li> ...</li>
</ul>
<h2>Sub Category</h2>
<ul>
<li>Post 1</li>
<li> ...</li>
</ul>
This is my code
<?php
$post_type = 'biblioteka';
$tax = 'kategoria-pozycji';
$tax_terms = get_terms( $tax );
if ($tax_terms) {
foreach ($tax_terms as $tax_term) {
$args = array(
'post_type' => $post_type,
'child_of' => $tax_term->term_id,
"$tax" => $tax_term->slug,
'post_status' => 'publish',
'posts_per_page' => 2,
'hierarchical' => true,
'caller_get_posts'=> 1);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) : ?>
<h1><?php echo $tax_term->name; ?></h1>
<ul>
<?php while ( $my_query->have_posts() ) : $my_query->the_post(); ?>
<li id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
<?php else : ?>
<?php endif; wp_reset_query();
}
}
?>
Thanks for all help!
Upvotes: 1
Views: 2280
Reputation: 21
Thanks all for help... This is 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>';
}
}
?>
Upvotes: 1