Displaying Link Count of Each WordPress Category Inside The <a> Tag Itself

As you probably know, to get the category list in WordPress, you use:

<ul>
<?php wp_list_categories('orderby=name&show_count=1&title_li='); ?>
</ul>

Is it possible to get it without <li>, and display link counts of each category inside the <a> tag itself?

Read More

For example, I want to use this structure for categories:

<nav>
    <a href="?cat=1">Arabesque (3)</a>
    <a href="?cat=2">Business (5)</a>
</nav>

instead of this typical one:

<nav>
<ul>
    <li><a href="?cat=1">Arabesque</a> (3)</li>
    <li><a href="?cat=2">Business</a> (5)</li>
</ul>
</nav>

Related posts

3 comments

  1. The best way is to use a filter:

    add_filter( 'wp_list_categories', 'mytheme_category_list' );
    function mytheme_category_list( $list ) {
        //remove ul tags
        $list = str_replace( '<ul>', '', $list );
        $list = str_replace( '</ul>', '', $list );
        //remove li tags
        $list = preg_replace( '~<li(.*?)>~s', '', $list );
        $list = str_replace( '</li>', '', $list );
        //move count inside a tags
        $list = str_replace( '</a> (', '(', $list );
        $list = str_replace( ')', ')</a>', $list );
        return $list;
    }
    
  2. To move the post count inside the a tag, use this snippet in your functions.php file:

    function prefix_move_category_count( $links ) {
        $links = str_replace( '</a> <span class="count">', ' <span class="count">', $links );
        $links = str_replace( '</span>', '</span></a>', $links );
        return $links;
    }
    add_filter( 'wp_list_categories', 'prefix_move_category_count' );
    

    Source: https://gist.github.com/blainerobison/1f1e59c99f5c9a78b93d

  3. Got it from GitHub https://gist.github.com/blainerobison/1f1e59c99f5c9a78b93d

    Works Perfectly

    /**
    * Move Category Post Counts Inside Link
    *
    * filters wp_list_categories()
    *
    * @param string $links link html output
    * @return string
    */
    function prefix_move_category_count( $links ) {

    $links = str_replace( '</a> <span class="count">', ' <span class="count">', $links );
    $links = str_replace( '</span>', '</span></a>', $links );
    
    return $links;
    

    }
    add_filter( ‘wp_list_categories’, ‘prefix_move_category_count’ );

    /**
    * Move Archive Post Counts Inside Link
    *
    * filters get_archives_link()
    *
    * @param string $links link html output
    * @return string
    */
    function prefix_move_archive_count($links) {

    $links = str_replace( '</a>&nbsp;(', ' <span class="count">(', $links );
    $links = str_replace( ')', ')</span></a>', $links );
    
    return $links;
    

    }
    add_filter( ‘get_archives_link’, ‘prefix_move_archive_count’ );

Comments are closed.