TV Show Tees - T-shirts and gifts of all your favorite television programs
Home » Web Things » Customizing a list of Wordpress categories with PHP

Customizing a list of Wordpress categories with PHP


by Arthur
Posted on Saturday, June 3rd, 2006 at 8:20 pm CET

The standard way to display a list of categories in a Wordpress template is by using the wp_list_cats template tag, but sometimes you may want to customize the list of categories and display them in a different way.

Here is the PHP code to retrieve all categories into an array:


< ? /* get all posts and put it in an array $allposts */
$allposts = get_posts();

/* run through the $allposts array to get all categories */
foreach($allposts as $post) :

     /* put all categories of this post in $category array */
     $category = get_the_category();

     foreach ($category as $categoryidfound) :

          /* retrieve category ID and store in $cats array */
          $cats[$categoryidfound->cat_ID] = _
                  $categoryidfound->cat_name;        		

          /* count number of posts and store in $numbers array */
          $numbers[$categoryidfound->cat_ID] = _
                  $numbers[$categoryidfound->cat_ID]+1;
     endforeach;
endforeach;

/* sort all categories alphabetically and flip values in array */
uasort($cats, strcasecmp);
$cats = array_flip($cats); ?>

Now you can display them in a numbered list:

(note: the following code puts the (n) of number of posts inside the <a href> tag. This is not normally done when you’re using wp_list_cats, but you may need it when for instance you are treating the a tag as a block in your css and you don’t want the (n) to be displayed on the next line)


< ? echo "
    “; foreach($cats as $current_cat) : ?>
  • “;

Or display a list of posts beneath each category name:


< ? echo "




“;
endforeach;
echo “”; ?>

< ?php

blinkbits BlinkList blogmarks co.mments connotea del.icio.us De.lirio.us digg Fark feedmelinks Furl LinkaGoGo Ma.gnolia
NewsVine Netvouz RawSugar Reddit scuttle Shadows Simpy Smarking Spurl TailRank Wists YahooMyWeb

Leave a Reply