Add Thumbnail to wp_list_categories()

The original question uses get_tax_meta() which does not exist in WordPress core but may be a custom function created by the asker. In this case we could switch it out just as well with get_term_meta().

You could try this:

class List_Category_Images extends Walker_Category {
    function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) {
        $saved_data = get_tax_meta( $category->term_id, 'image_field_id', true );

        $cat_name = apply_filters(
            'list_cats',
            esc_attr( $category->name ),
            $category
        );

        $link = '<a href="' . esc_url( get_term_link( $category ) ) . '" ';
        if ( $args['use_desc_for_title'] && ! empty( $category->description ) ) {
            $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"';
        }

        $link .= '>';
        $link .= '<img src="' . $saved_data['src'] . '">';
        $link .= $cat_name . '</a>';

        if ( ! empty( $args['show_count'] ) ) {
            $link .= ' (' . number_format_i18n( $category->count ) . ')';
        }
        if ( 'list' == $args['style'] ) {
            $output .= "\t<li";
            $class="cat-item cat-item-" . $category->term_id;
            if ( ! empty( $args['current_category'] ) ) {
                $_current_category = get_term( $args['current_category'], $category->taxonomy );
                if ( $category->term_id == $args['current_category'] ) {
                    $class .=  ' current-cat';
                } elseif ( $category->term_id == $_current_category->parent ) {
                    $class .=  ' current-cat-parent';
                }
            }
            $output .=  ' class="' . $class . '"';
            $output .= ">$link\n";
        } else {
            $output .= "\t$link<br />\n";
        }
    }
}

What I’m doing is modifying one of the methods inside the Walker_Category class which in this case the function is actually creating the link to the term / category. At the top of the method I call the get_tax_meta() function ( which I assume works, as this is not built into WordPress ). Then I add the image directly before the name of the category:

$link .= '>';
$link .= '<img src="' . $saved_data['src'] . '">';
$link .= $cat_name . '</a>';

Now all you need to do is define a new instance of this class in your wp_list_categories() function:

$args = array(
    'orderby'       => 'name',
    'show_count'    => 0,
    'pad_counts'    => 0,
    'hierarchical'  => 1,
    'taxonomy'      => $tax,
    'walker'        => new List_Category_Images
);
wp_list_categories( $args );

Leave a Comment