Archived topic
overview of all categories with the respective category description
5 replies · Started by Friedhelm on January 14, 2022
I would like to create a page/ a Block with an overview of all categories with the respective category description. At the moment I do it "by hand". How can you do that with GPP? I look forward to your reply.
Hi there,
thats not a theme thing, but you can use the WP get_categories function to return the list of category terms and descriptions:
https://developer.wordpress.org/reference/functions/get_categories/
I used that to create this PHP Snippet:
add_shortcode('cat_listing', function($html){
$html = '';
$categories = get_categories('exclude=1&title_li=');
foreach ($categories as $cat) {
$html .= "<h2>".$cat->cat_name."</h2><p>".$cat->category_description."</p>";
}
return $html;
});
If you add that to your site: https://docs.generatepress.com/article/adding-php/
Then you can use add this shortcode to your page: [cat_listing]
Dear David,
Thank you for your quick support. The PHP snippet works great. However, the first category (= Ausstellung) was not displayed. After removing "exclude=1" it works (see here). Is that okay?
It would be nice if the categories also had the corresponding links. And even more perfect if the post count was also displayed. Do you also have an idea for this?
Ooops not sure why i left those args in....
Ok for the changes you want to make use this Snippet instead:
add_shortcode('cat_listing', function($html){
$categories = get_categories();
$html = '';
foreach( $categories as $category ) {
$category_link = sprintf(
'<a href="%1$s" alt="%2$s">%3$s</a>',
esc_url( get_category_link( $category->term_id ) ),
esc_attr( $category->name ),
esc_html( $category->name )
);
$html .= '<h2>' . $category_link . '<sup>(' . $category->count . ')</sup></h2>';
$html .= '<p>' . $category->description . '</p>';
}
return $html;
});
Dear David,
now it works great, just like I imagined. Thank you and 5 stars for the support from GP. (see Link here)
Awesome - that looks great. Glad to be of help.