WordPress.org

Support

Support » How-To and Troubleshooting » Display child categorie uniquely according to active parent categories

Display child categorie uniquely according to active parent categories

  • Hi guys,

    Awesome Wednesday huh!? Well, I am using the default WordPress category listing and I want to display child taxonomies according to the parent taxonomies.

    At the moment I have the parent category as a menu (Shoes | Pants | Weapons, etc). If you click on ‘Shoes’ you goto: http://www.example.co.za/category/shoes

    I then want to show only the children category terms for shoes on the shoes page, ie:
    = Shoes (parent)
    – Gucci (child)
    – NoName (child)
    – Diesel (child)

    At the moment the children category terms are displayed on all the parent categories. I get shoes under the ‘Pants’ category. How do I filter?

    My current code below:

    $taxonomyName = "category";
    			//This gets top layer terms only.  This is done by setting parent to 0.
    			$parent_terms = get_terms(
    					$taxonomyName, array(
    							'parent' => 0,
    							'orderby' => 'slug',
    							'hide_empty' => false
    							)
    					);
    
    			echo '<ul id="sub-filter">';
    			foreach ($parent_terms as $pterm) {
    				//Get the Child terms
    				$terms = get_terms($taxonomyName, array(
    						'parent' => $pterm->term_id,
    						'orderby' => 'slug',
    						'hide_empty' => false
    						)
    					);
    				foreach ($terms as $term) {
    					echo '<li>'. $term->name . '</a></li>';
    				}
    			}
    			echo '</ul>';

Viewing 1 replies (of 1 total)
  • Moderator keesiemeijer

    @keesiemeijer

    Try it with cat_is_ancestor_of(): http://codex.wordpress.org/Function_Reference/cat_is_ancestor_of
    [untested]

    <?php
    	$taxonomyName = "category";
    	$current_cat =  get_query_var('cat');
    			//This gets top layer terms only.  This is done by setting parent to 0.
    			$parent_terms = get_terms(
    					$taxonomyName, array(
    							'parent' => 0,
    							'orderby' => 'slug',
    							'hide_empty' => false
    							)
    					);
    
    			echo '<ul id="sub-filter">';
    			foreach ($parent_terms as $pterm) {
    			  if(cat_is_ancestor_of($pterm->term_id, $current_cat)){
    				  //Get the Child terms
    				  $terms = get_terms($taxonomyName, array(
    						'parent' => $pterm->term_id,
    						'orderby' => 'slug',
    						'hide_empty' => false
    						)
    					);
    				  if($terms)
    				  foreach ($terms as $term) {
    					  echo '<li>'. $term->name . '</a></li>';
    				  }
    				}
    			}
    			echo '</ul>';
    	 ?>

Viewing 1 replies (of 1 total)
  • The topic ‘Display child categorie uniquely according to active parent categories’ is closed to new replies.