我在walker类的基础上取得了一些进展,但由于wordpress似乎没有以与子节点相同的方式处理分类树的根节点,因此我还没有让ti完全按照需要工作。
因此,它会修剪结束菜单项,但如果该节点的父节点是根级别的节点,则会修剪该节点并留下一个空的ul元素,<ul></ul>
. 在子节点上修复此问题的代码不适用于根节点,导致整个结构扁平化,没有子菜单
class Post_Category_Walker extends Walker_Category {
private $term_ids = array();
function __construct( /*$post_id,*/ $taxonomy ) {
// fetch the list of term ids for the given post
$this->taxterms = get_terms( $taxonomy);
$this->noshow = array();
}
function isdisplayable( $element, &$children_elements, $args ){
$id = $element->term_id;
if(in_array($element->term_id, $this->noshow)){
return false;
}
$display = true;
if($element->parent != 0){
$display = false;
if ( isset( $children_elements[ $id ] ) ) {
$display = true;
}
}
if($depth == 0){
$display = true;
}
return $display;
}
function hasChildren( $element/*, &$children_elements*/){
foreach($this->taxterms as $term){
if($term->parent == $element->term_id){
return true;
}
}
return false;//(isset($children_elements[$element->term_id]));
}
function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) {
$display = $this->isdisplayable( $element, $children_elements, $args );
$id = $element->term_id;
if($element->parent != 0){
if($this->hasChildren($element)){ //isset( $children_elements[ $id ] ) ) {
$endnode = true;
//print_r($children_elements[ $id ]);
foreach($this->taxterms as $child){
if($child->parent == $element->term_id){
if($this->hasChildren($child)){
$endnode = false;
break;
}
}
}
if($endnode == true){
//$children_elements = NULL;
unset( $children_elements[ $id ] );
$newlevel = false;
$args[0][\'has_children\'] = 0;
}
}
}else{
// Wordpress separates out the terms into top level and child terms,
// making the top level terms very costly as it passes in an empty
// array as the children_elements unlike the other terms
//if($this->hasChildren($element)){
foreach($this->taxterms as $term){
if($term->parent == $element->term_id){
if(!$this->hasChildren($term)){
$this->noshow[] = $term->term_id;
unset($newlevel);
$args[0][\'has_children\'] = 0;
}
}
}
//}
}
if ( $display )
parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output );
}
}
$a = array(
\'title_li\' => \'\',
\'taxonomy\' => \'productcategory\',
\'walker\' => new Post_Category_Walker(\'productcategory\')
);
wp_list_categories( $a );
临时解决方法是通过以下jquery代码段删除它们:
$("ul").each(
function() {
var elem = $(this);
if (elem.children().length == 0) {
elem.remove();
}
}
);