Month: July 2017

WordPress custom taxonomy custom hierarchical

Custom taxonomy hierarchical with ul li list and checkbox and radio button.


function get_product_taxonomie($taxonomies = 'product_category', $input_type = 'radio', $input_class = 'categoryCheck') {function get_product_taxonomie($taxonomies = 'product_category', $input_type = 'radio', $input_class = 'categoryCheck') { $selected_term = ''; $selected_term_open = ''; if($taxonomies == 'product_category'){ $selected_term = get_query_var('cats'); $selected_term_open = get_query_var('cats'); if(empty($selected_term)){ $selected_term = get_queried_object()->term_id; $selected_term_open = get_queried_object()->term_id; } } else if($taxonomies == 'product_brand'){ $selected_term = get_query_var('brands'); $selected_term_open = get_query_var('brands'); if(empty($selected_term)){ $selected_term = get_queried_object()->term_id; $selected_term_open = get_queried_object()->term_id; } } $selected_term = explode(',', $selected_term); $args = array( 'orderby'           => 'name',  'order'             => 'ASC', 'hide_empty'        => false,  'fields'            => 'all', 'parent'            => 0, 'hierarchical'      => true, 'child_of'          => 0, 'pad_counts'        => false, 'cache_domain'      => 'core' ); $terms = get_terms($taxonomies, $args); $return .= '<ul class="'.$taxonomies.'">';    foreach ( $terms as $term ) { $subterms = get_terms($taxonomies, array( 'parent'   => $term->term_id, 'hide_empty' => false )); $has_sub = ""; if( is_array($subterms) && !empty($subterms) ){ $has_sub = " has-children"; if(in_array_r($subterms, 'term_id', $selected_term_open)){ $has_sub .= " open"; } } $checked = ''; if(in_array($term->term_id, $selected_term)){ $checked = 'checked'; } // return terms (working) $return .= sprintf( '<li id="category-%1$s" class="toggle%6$s"><label><input type="%3$s" value="%1$s" name="%4$s" class="%5$s" %7$s><span>%2$s</span></label>', $term->term_id, $term->name, $input_type, $term->taxonomy, $input_class, $has_sub, $checked #7 ); if( is_array($subterms) && !empty($subterms) )        $return .= '<ul class="children">';
foreach ( $subterms as $subterm ) { $checked = ''; if(in_array($subterm->term_id, $selected_term)){ $checked = 'checked'; } $return .= sprintf( '<li id="category-%1$s" class="toggle"><label><input type="%3$s" value="%1$s" name="%4$s" class="%5$s" %6$s><span>%2$s</span></label>', $subterm->term_id, $subterm->name, $input_type, $term->taxonomy, $input_class, $checked # 6 ); $return .= '</li>'; //end subterms li } if( is_array($subterms) && !empty($subterms) )        $return .= '</ul>'; //end subterms ul $return .= '</li>'; //end terms li } //end foreach term $return .= '</ul>'; return $return;}
/** add current page active class */function in_array_r($array, $key, $val) {    foreach ($array as $item){ if (isset($item->$key) && $item->$key == $val){ return true; } } return false;}

Advertisements