WordPress.org

Ready to get started?Download WordPress

Forums

Display child categorie uniquely according to active parent categories (2 posts)

  1. Archie22is
    Member
    Posted 1 year ago #

    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>';
  2. keesiemeijer
    moderator
    Posted 1 year ago #

    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>';
    	 ?>

Topic Closed

This topic has been closed to new replies.

About this Topic