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 = '<div class="testimonial"><p>“$content” — <cite>$credit</cite></p></div>';
    }

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

Let’s keep in touch

Get noise-free updates on software, product, and process.

Hey, I'm RJ: digital entomologist and intermittent micropoet, writing from the beautiful Rose City.