DEV Community

Cover image for WordPress Categories with post count
SnippFlow
SnippFlow

Posted on

2 1 1

WordPress Categories with post count

The shortcode displays a list of categories with post count on your WordPress site.

PHP

// ---------------------------------------------------------- //
//           Snippflow Categories with post count             //
// ---------------------------------------------------------- //

function sf_categories_with_post_count() {
  $categories = get_categories();
  $output = '<ul class="sf-categories">';
  foreach ($categories as $category) {
      $output .= '<li><a href="' . esc_url(get_category_link($category->term_id)) . '">' . $category->name . '<span>' . $category->count . '</span></a></li>';
  }
  $output .= '</ul>';
  return $output;
}
add_shortcode('sf_categories_with_post_count', 'sf_categories_with_post_count');
Enter fullscreen mode Exit fullscreen mode

CSS:

/* ---------------------------------------------------------- */
/*            Snippflow Categories with post count            */
/* ---------------------------------------------------------- */
.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; }
Enter fullscreen mode Exit fullscreen mode

Full article: WordPress Categories with post count
CSS Snippets

πŸ‘‹ While you are here

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay