Two column category lists in Wordpress
Oct1st
2008
••
Here’s another installment of making columns in Wordpress. This time around I am going to show how to pull your catergories and make a two column list out of them. The PHP involved is very close to the PHP used in “Two Column Magazine Style Posts” so I won’t go into as much detail about the redundant code. I will add my ideas on the new additions though.
Now one thing to consider, like in my “Two Column Lists” artcle, is that this will produce invalid code. The caveat is that the code, although invalid, will work and format correctly causing no ill-effects to the user. All that is being tagged as a warning is the insertion of a <span>. This will cause resulting warnings for all the caode follwing it as well. So again, use it at your discretion.
Much like other CSS in my examples, it’s pretty staright forward.
#text #ian { margin: 0; padding: 0; }
#text #ian li { padding: 0; margin: 0; list-style: none outside; border-bottom: 1px solid #AF5341;}
#text #ian li a { text-decoration: none; display: block; }
#text #ian span { width: 230px; float: left;}
#text #ian span.right { display: inline; margin: 0 0 0 30px;}
Here is the whole code for reference.
<ul id="ian">
<?php
$categories = get_categories('order=DESC&orderby=count');
$i = 0;
foreach ($categories as $category){
$i++ ;
$q = $i - 1;
}
$z = round($q/2);
$i = 0;
echo "<span>"."n";
foreach ($categories as $category){
$i++ ;
$q = $i - 1;
if ($i != 0) {
echo "<li><a href='category/".$category->cat_name."'>".$category->cat_name."(".$category->category_count.")</a></li>"."n";
}
if ($i == $z 1 ){
echo "</span>"."n"."<span class='right'>"."n";
}
}
echo "</span>"."n"
?>
</ul>
So now the differences in this code are pretty simple. First we tell Wordpress to grab all the categories and sort them in descending order by total number of posts in each category. The we count each one to create a variable.
$categories = get_categories('order=DESC&orderby=count');
$i = 0;
foreach ($categories as $category){
$i++;
$q = $i - 1;
}
Then we take that information and build a list, counting each category and then at the halfway point +1 we insert the closing left span and the new right span.
$z = round($q/2);
$i = 0;
echo "<span>"."n";
foreach ($categories as $category){
$i++;
$q = $i - 1;
if ($i != 0) {
echo "
<li><a href="http://tugbucket.net/wp-admin/category/%22.$category-%3Ecat_name.%22">".$category->cat_name."(".$category->category_count.")</a></li>
"."n";
}
if ($i == $z 1 ){
echo "</span>"."n"."<span class="right">"."n";
}
}
echo "</span>"."n"
?>
I used th PHP line breaks so the resulting code would look correct when the source is viewed.
Here’s a working example of my category list.
As with any of my code I am posting here, if you find an error please let me know. When converting my code to ACII, some items can get left out causing the whole ting to fail.












