Our site, keeping you up-to-date news.

 

Get a Random Post From a Category

February 26, 2012 at 10:51 am | Blog | No comment

 

When i was trying to implement a new feature for corporattica theme, i wanted to get a random post from a category. btw, the new feature is to display a static picture for pages except for the home page, as users found that the sliders in normal pages disturbing.

At the beginning, i think about the most straight forward way, to know the number of posts in the category, and then to use the rand() function of PHP to get a number between 0 and the count. And then use the “offset” of wordpress query parameter to show the random post. However, i did not find the function to get the count of posts in a specific category.

And then, i was thinking further and i switched to another direction. Although i can not the post counts in the category, i can always the get first post in the category. If the first post in the category is random for each query, then my requirements fulfilled. We can order the queried posts randomly, and the first post in this list is also random. And the best part is, wordpress has already had this feature.

$args = array( 'category'=>'featured','numberposts' => 1, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );

Sometimes the best way is not the straight forward way. And now the corporattica theme has the new feature of displaying a random static picture for pages other than Home Page.