My code uses a taxonomy category image plugin to display images for categories. It also displays subcategories of the main category in the parent category page (category.php
). I want to display only one level of subcategories in the page, for example:
hardware (parent category)
-
monitor (first level subcategory of harware)
-
samsung (second level subcategory)
- lcd (third level subcategory )
-
When the user clicks on the hardware link, they should see only the monitor subcategory link. Clicking on monitor, they should see the samsung category link, and when they click on samsung, lcd should display.
How I should change my code to achieve this?
My code:
<?php
$cat_id = get_query_var('cat');
$catlist = get_categories('hide_empty=0&child_of=' . $cat_id);
echo "<ul>";
foreach($catlist as $categories_item)
{
echo '<h1><a href="' . get_category_link( $categories_item->term_id ) . '" title="' . sprintf( __( "View all products in %s" ), $categories_item->name ) . '" ' . '>' . $categories_item->name.'</a> </h1> ';
echo '<div class="categoryoverview clearfix">';
$terms = apply_filters( 'taxonomy-images-get-terms', '' );
if ( ! empty( $terms ) ) {
foreach( (array) $terms as $term ) {
if($term->term_id == $categories_item->term_id) {
print '<a href="' . esc_url( get_term_link( $term, $term->taxonomy ) ) . '">' . wp_get_attachment_image( $term->image_id, 'thumbnail' );
echo '</a>';
}
}
echo '<p>'. $categories_item->description; echo '</p>';
}
echo '</div>';
}
echo "</ul>";
?>
Change the second line of your code to this:
Instead of
child_of
parameter, use theparent
parameter of theget_categories()
function; this will display the direct descendants (i.e. children only) of the category and not grandchildren of the category.For more information visit the Codex page for
get_categories()
.