Displaying random posts using shortcode

Random posts can be a great opportunity to generate hits for older content. Especially for gaming and portfolio sites this snippet will be great use. Here is how to set it up for your theme.

1. Setting up

To display a list of random posts, first add the following code to your functions.php file.

function stf_random_posts( $post_count = 5, $template = 'loop' ){
	
	// Generate query
	$query_arguments = array(
		'ignore_sticky_posts'=>1,
		'posts_per_page' => $post_count,
		'orderby'=>'rand'
	);
	
	// Query posts
	query_posts( $query_arguments );
	
	// Loop posts
	if ( have_posts() ) : 
		$post_index = 1; 
		while ( have_posts() ) : the_post();
			get_template_part( $template , get_post_format() );
			$post_index = $post_index + 1; 
		endwhile;
	endif;
	
	// Reset to default query
	wp_reset_query();	
}

function stf_random_posts_shortcode( $atts, $content = null ){
	extract(shortcode_atts( array(
		'count' => 5,
		'template' => 'loop'
	), $atts));
	
	stf_random_posts( $count, $template );
}

add_shortcode('randomposts', 'stf_random_posts_shortcode');

This code adds a php function and a shortcode to use in posts.
To display posts you need a loop.php file at least. Here is a sample loop.php file:

<li class="entry-<?php the_ID(); ?>">
	<a href="<?php the_permalink(); ?>" rel="bookmark"><?php the_title(); ?></a>
</li>

Save this code as loop.php in your theme directory.

2. Usage

You can either use php code or shortcode version. PHP snippet to use in your theme files:

 <?php stf_random_posts( 5, 'loop' ); ?>

You can also use shortcode in your posts:

[randomposts count=3 template='loop']

3. Bonus Tip

Tip1. This code displays posts using loop.php file. If post formats are used in your theme, it will first look for a template file named loop-%format%.php. For example if you have a post with an image post format it will be displayed using loop-image.php file. Using this algorithm, you can create different loop files for different content types.

Tip2. You can change template prefix as you like. For example, to generate a list of posts you can create a template called list.php and then use this code :

[randomposts count=3 template='list']

In this way, you can display posts in many different ways using multiple template files.

Enjoy!



NS Weight Release

WP-Backgrounds Lite by InoPlugs Web Design and Juwelier Schönmann 1010 Wien