It seems to me that category_description
should be an option in wp_list_categories
. Is there way to pull the description when listing all categories?
1 Answer
Extend the Walker_Category
class
We can extend the Walker_Category
class to append the category description to each item.
Here's a demo example with an anonymous class (PHP 7+):
$args = [
'walker' => new class extends Walker_Category
{
public function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 )
{
// Let's use the output from the parent's start_el method
$output .= parent::start_el( $output, $category, $depth, $args, $id );
// Append the category description:
$desc = $category->description;
$output .= ( $desc ) ? sprintf( '<span>%s</span>', esc_html( $desc ) ) : '';
}
}
];
wp_list_categories( $args );
For older PHP versions, we can just define the class as usual with a custom name.
Here's a single item output example:
Item before:
<li class="cat-item cat-item-269">
<a href="http://example.tld/category/green/"
title="Description for the Green category">Green</a>
</li>
Item after:
<li class="cat-item cat-item-269">
<a href="http://example.tld/category/blue/"
title="Description for Green category">Green</a>
<span>Description for the Green category</span>
</li>
get_categories()
which will give you more freedom on what to display and how to display it. Also, there is an optionuse_desc_for_title
if that's what you're trying to do.