Pick one or more random category id’s from wordpress

Views: 32 Last modified: August 02nd, 2011 Comments: 0

This php function, written for wordpress, gives you the opportunity to grab a X amount of category id’s, excluding empty one’s.
It accepts just one parameter which would be the amount of category id’s you want.

After the function has done it’s job, it will return an array, containing the amount of requested category id’s.

<?php
/**
 * PickRandomCategory()
 * Returns X category ids.
 * @param int $amount
 * @return array $return
 */
function PickRandomCategory($amount){
if (!is_int($amount))
    return false;

mt_srand((double)microtime()*1000000);
$ids = array();
$return = array();
    $cats = get_categories(array('hide_empty' => 1));
        foreach ($cats as $cat)
            $ids[] = $cat->cat_ID;

        shuffle($ids);

            for ($j = 0; $j < $amount; $j++){
                $return[] = $ids[$j];
            }
    return $return;
}

// $random_cat will now have 3 array elements - filled with id's.
$random_cat = PickRandomCategory(3);
?>
VN:F [1.9.13_1145]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.13_1145]
Rating: 0 (from 0 votes)

    Mail this!

    To: From:Sum {0+7} =  
    Anything to add ?

        You must be logged in to post a comment.