Home > Backend Development > PHP Tutorial > WordPress Categories with post count

WordPress Categories with post count

Susan Sarandon
Release: 2025-01-17 00:04:13
Original
863 people have browsed it

WordPress Categories with post count

This shortcode neatly displays your WordPress categories alongside their respective post counts.

PHP Code:

<code class="language-php">// ---------------------------------------------------------- //
//           Custom WordPress Category Display                //
// ---------------------------------------------------------- //

function display_categories_with_count() {
    $categories = get_categories();
    $output = '<ul class="sf-categories">';
    foreach ($categories as $category) {
        $output .= '<li><a href="' . get_category_link($category->term_id) . '">' . $category->name . '<span>(' . $category->count . ')</span></a></li>';
    }
    $output .= '</ul>';
    echo $output;
}

add_shortcode('category_count', 'display_categories_with_count');</code>
Copy after login

CSS Styling:

<code class="language-css">/* ---------------------------------------------------------- */
/*           Styled Category List for WordPress              */
/* ---------------------------------------------------------- */
.sf-categories { display: flex; flex-direction: column; gap: 8px; list-style: none; margin: 0; padding: 0; }
.sf-categories li { position: relative; padding: 0; }
.sf-categories li a { display: flex; background-color: #fff; color: #000; border-radius: 8px; padding: 10px 16px; font-size: 1rem; text-decoration: none; transition: all .2s ease-in-out; }
.sf-categories li a span { display: block; position: absolute; right: 16px; top: 50%; transform: translateY(-50%); padding: 3px 8px; font-size: 0.85rem; line-height: 1; background-color: rgba(0,0,0,.05); border-radius: 4px; }
.sf-categories li a:hover { background-color: #46A787; color: #fff; }
.sf-categories li a:hover span { background-color: rgba(255,255,255,.1); color: #fff; }</code>
Copy after login

Complete Guide: Enhance your WordPress site with this styled category list and post count. Use the provided shortcode [category_count] within your posts or pages.

The above is the detailed content of WordPress Categories with post count. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template