Including a random custom post in your Wordpress Theme
- 1/5/2011
The addition of custom post types in WP3+ allows theme designers to include random post types within their themes. Here’s one example that could be used to display a random post of the custom ‘testimonial’ type somewhere in the theme:
function random_testimonial( $output = true ) {
$posts = get_posts( array(
'post_type' => 'testimonial',
'numberposts' => 1,
'orderby' => 'rand'
) );
$result = '';
if( is_array( $posts ) && count( $posts ) == 1 ) {
$post = array_shift( $posts );
$content = apply_filters( 'the_content', $post->post_content );
$credit = apply_filters( 'the_title', $post->post_title );
// print a testimonial
$result = '<div class="testimonial"><p>“$content” — <cite>$credit</cite></p></div>';
}
return $output ? print( $result ) : $result;
}