jmhobbs

WordPress jh_random_cats()

Got bored and scratched another itch I've had in wordpress for a while. I always wanted a way to list my categories on the sidebar on my terms. The best I had found was the well written and executed Category Visibility-RH but I wanted to choose from all my categories and still limit the number listed.

I added a function to my wp-hacks.php and then dropped it into my sidebar. Does the job, and could easily be edited. I swear someday I'll learn how to make plug-ins, really.

function jh_random_cats($howMany) {
    global $wpdb ;

		$query = "
			SELECT cat_ID, cat_name, category_count
			FROM $wpdb->categories
      WHERE category_count != '0'
    ";
		$categories = $wpdb->get_results($query);
		
		shuffle($categories); // Mix 'em up
		
		for($howMany; $howMany > 0; $howMany--) {
      $poppedCat = array_pop($categories);
      print '
  • '.$poppedCat->cat_name.' ('.$poppedCat->category_count.')
  • '; } }

    As a super-cool extra I got to use a PHP function I had never gotten to use before, let alone knew existed: bool shuffle ( array &array ). It, you guessed it, shuffles up an array.