Question

How could I include the count of posts under a category into the a-tag when listing categories. This has been a problem for me many times but now I decided to find out.

<li><a href="#" title="asd">php</a> (1)</li>

to

<li><a href="#" title="asd">php (1)</a></li>

Is you propably assumed, I'm using wp_list_categories to make this list.

Any solutions?

Martti Laine

Was it helpful?

Solution

I solved it. Posting here so someone can use it :)

<?php
$data = wp_list_categories('show_count=1&echo=0');
$data = preg_replace('/\<\/a\> \((.*)\)/',' ($1)</a>',$data);
echo $data;
?>

OTHER TIPS

I recently had this problem as well. Other forums I read suggested regex too and personally that option seemed prone to flaw.

My recommendation is this:

$cat_args = array(
    'orderby' => 'count',
    'order' => 'DESC'
);

$categories = get_categories( $cat_args );

if ( count($categories) ) {

    echo '<ul>';

    foreach ( $categories as $category ) {
        echo '<li><a href="'.get_category_link( $category->term_id ).'">'.$category->name.' ('.$category->count.')</a></li>';
    }

    echo '</ul>';

}

It also gives you the option to format the number in something other than parens if you wish.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top