Talking about Php and WordPress.
Today I want to show you how I solved a problem I had with my WordPress blog just by adding a couple of lines of code.
I wanted to show only some categories on the header, as you can clearly see I only show these ones: Game Design, Monetize, Javascript, HTML5, Phaser, Box2D, ActionScript 3, Flash and I don’t show, WordPress and Php which also are blog categories, as you can see in this post.
Well, that was simple, I only had to edit the theme and add
get_categories(array("include"=>"5,6,17,22,23,27,42,44");
using get_categories you can select only some categories to show, but there’s a big missing feature in my opinion: you can’t decide in which order to display.
Default order is alphabetical order, then you only have a few more options like the number of posts, but you can’t give your categories a real custom order.
Obviously a lot of plugins come out to let bloggers give custom order to their categories, some of them written from scratch, some others starting from Advance Custom Fields plugin.
To keep my theme light and clean, I prefer not to use any plugin for easy tasks like this: let’s see how I solved this problem:
$category_order = array(22,17,6,42,44,27,23,5); $category_array = array(); $categories=get_categories(array("include"=>"5,6,17,22,23,27,42,44")); if ($categories) { foreach($categories as $category) { $category_array[array_search($category->cat_ID,$category_order)] = '<div class = "maincats"><a href = "/category/'.$category->category_nicename.'">' . $category->name."<br />".$category->count."</a></div>"; } ksort($category_array); foreach($category_array as $category){ echo $category; } }
Line 1: this is an array containing the actual order I want to give to my categories. These are the IDs of each category.
Line 2: this is the array which will contain the HTML of the sorted categories.
Line 3: let’s get the categories!
Line 4: just checking if categories exist, in case you mispelled categories IDs.
Line 5: looping trough all categories.
Line 6: placing in the final categories array the HTML for each category, in the proper index according to the order I set at line 1.
Line 8: sorting the final categories array, by key.
Line 9: looping trough the final categories array.
Line 10: finally writing the HTML of each category in the right order.
And that’s it, I had my categories ordered by my custom order. Easy and nice, without any plugin.
Never miss an update! Subscribe, and I will bother you by email only when a new game or full source code comes out.