2

I am trying to achieve something that seems like it should be simple but is causing me headaches. I am listing my categories out using wp_list_categories which gives me this...

<ul>
<li>Fruit</li>
<li>Vegetables</li>
<li>Tinned Goods</li>
<li>Dairy Products</li>
</ul>

All I want to do is add a class to the ul and li using a walker function, my function looks like this....

class Walker_Simple_Example extends Walker {  
    var $db_fields = array( 'parent' => 'parent_id', 'id' => 'object_id' );  

    function start_lvl(&$output, $depth=1, $args=array()) {  
        $output .= "\n<ul class=\"product_cats\">\n";  
    }  

    function end_lvl(&$output, $depth=0, $args=array()) {  
        $output .= "</ul>\n";  
    }  

    function start_el(&$output, $item, $depth=0, $args=array()) {  
        $output .= "<li class=\"item\">".esc_attr( $item->name );
    }  

    function end_el(&$output, $item, $depth=0, $args=array()) {  
        $output .= "</li>\n";  
    }  
}  

This works fine for the li items and gives them all a class of 'item' but the ul class just doesn't appear. Can anyone see where I am going wrong?

10

You should be extending Walker_Category not the main Walker class.

class Walker_Simple_Example extends Walker_Category {  

    function start_lvl(&$output, $depth=1, $args=array()) {  
        $output .= "\n<ul class=\"product_cats\">\n";  
    }  

    function end_lvl(&$output, $depth=0, $args=array()) {  
        $output .= "</ul>\n";  
    }  

    function start_el(&$output, $item, $depth=0, $args=array()) {  
        $output .= "<li class=\"item\">".esc_attr( $item->name );
    }  

    function end_el(&$output, $item, $depth=0, $args=array()) {  
        $output .= "</li>\n";  
    }  
}  

wp_list_categories(array('walker'=> new Walker_Simple_Example));

That does work now. product_class is applied to the child uls but your walker does not preserve much of the default functionality.

If you want the class assigned to the parent <ul>, this is a bit over complicated. That <ul> comes from the wp_list_categories function itself, not from the walker. Disable the "title" which you don't seem to be using, and write in the wrapper <ul>.

echo '<ul class="product_cats">';
  wp_list_categories(array('title_li'=> false));
echo '</ul>';
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.