Skip to Content

Including a random custom post in your WordPress Theme

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 = '

“$content” — $credit

'; } return $output ? print( $result ) : $result; }