Skip to content

Instantly share code, notes, and snippets.

@nmedia82
Last active April 22, 2019 13:46
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save nmedia82/a1b3bc78d1137d26c256 to your computer and use it in GitHub Desktop.
Save nmedia82/a1b3bc78d1137d26c256 to your computer and use it in GitHub Desktop.
Rendering Taxonomy Tree for custom post types in Wordpress Plugin or Theme as checkbox input
/**
* Following script will render Taxonomy Tree attached with specified post type
* in following example post_type use: books
* output can be seen here: https://www.diigo.com/item/image/4xv00/xrhq
*/
$posttype = 'books'
//getting all taxonomies with attached with $posttype
$taxonomy_names = get_object_taxonomies( $posttype );
//looping taxonomies
foreach($taxonomy_names as $taxonomy){
echo '<label class="heading">'.$taxonomy.'</label>';
echo '<div class="clearfix"></div>';
//set these options as you required
$terms_args = array(
'hide_empty' => false,
'parent' => 0, );
//now pulling terms against each taxonomy
$terms = get_terms($taxonomy, $terms_args);
if($terms){
echo '<ul class="tax-styles">';
foreach ($terms as $term) {
//defined below, this function will render the terms and li recursively
render_term_tree($term->term_id, $taxonomy);
}
echo "</ul>";
}
}
/**
** this function is rendering terms RECURSIVELY
**/
function render_term_tree($termid, $taxonomy){
$single_term = get_term($termid, $taxonomy);
echo '<li>';
echo '<input type="checkbox" name="post_taxonomy['.$taxonomy.'][]" id="cat_'.$termid.'" value="'.$termid.'">';
echo '<label for="cat_'.$termid.'">'.$single_term->name.'</label>';
$childrens = get_term_children($termid, $taxonomy);
if($childrens){
//pa_postfront($childrens);
echo '<ul class="tax-styles">';
foreach ($childrens as $term_child) {
//recursive call if children found
render_term_tree($term_child, $taxonomy);
}
echo "</ul>";
}
'</li>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment