Skip to content

Instantly share code, notes, and snippets.

@baerkins
Created April 10, 2014 17:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save baerkins/10405449 to your computer and use it in GitHub Desktop.
Save baerkins/10405449 to your computer and use it in GitHub Desktop.
This gist creates a list of custom taxonomy terms in Wordpress. - It will display the child terms of a the current taxonomy term that is being viewed. - If the term being viewed is a child term, it will show the child terms of its parent. - The children of other terms will be hidden.
<?php
// List Custom Taxonomy Terms Based on Current View
// Setup global variables
$current_taxonomy = 'project_status';
$current_term_id = get_queried_object()->term_id;
$terms = get_terms($current_taxonomy);
// For a Single Post, get the ID of each term used
$allTerms= wp_get_object_terms($post->ID, $current_taxonomy);
// Put all term IDs into an array
$termsArray = array();
foreach ($allTerms as $eachTerm) {
$eachTermId = $eachTerm->term_id;
$termsArray[] = $eachTermId;
}
foreach($terms as $term) {
// Setup Term Variables
$termID = $term->term_id;
$termParent = $term->parent;
$termName = $term->name;
$termLink = get_term_link( $term, $current_taxonomy );
$termchildren = get_term_children( $termID, $current_taxonomy );
// Get Each Parent Category
if($termParent == 0) {
// If the term being written matches the term being displayed:
if($current_term_id == $termID || in_array($current_term_id, $termchildren) || in_array($termID, $termsArray) ) {
// If the current term is a parent, write the name and link, add current class
if($current_term_id == $termID) {
echo '<li class="current-cat"><a href="'. $termLink . '">All ' . $termName . '</a>'; // Note: this add 'All' to the begining of the line
} else {
echo '<li><a href="'. $termLink . '">All ' . $termName . '</a>'; // Note: this add 'All' to the begining of the line
}
// Write Child terms, names, and links
echo '<ul class="children">';
foreach ( $termchildren as $child ) {
$childTerm = get_term_by( 'id', $child, $current_taxonomy );
$childLink = get_term_link( $childTerm, $current_taxonomy );
$count = $childTerm->count;
if($count != 0) {
if($current_term_id == $child || is_single() && in_array($child, $termsArray)) {
echo '<li class="current-cat"><a href="'. $childLink .'">' . $childTerm->name . '</a></li>';
} else {
echo '<li><a href="'. $childLink .'">' . $childTerm->name . '</a></li>';
}
}
}
echo '</ul>';
// Close out the Parentlist
echo '</li>';
// Otherwise
} else {
echo '<li><a href="'. $termLink . '">All ' . $term->name . '</a></li>'; // Note: this add 'All' to the begining of the line
}
}
};
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment