Hay & Kilner Website Refresh
Hay & Kilner, a Facelift to an Existing CMS Driven Website
2 Comments
Walk To The World Cup - Campaign for Be Air Aware
Walk to the World Cup, a bespoke WordPress plugin
0 Comments
Service Network
Service Network, CMS based events driven website
0 Comments
Numark Pharmacists
Numark Pharmacists, CMS based website and membership based extranet
0 Comments

Show a Random Hero Banner Using Custom Post Types with WordPress 3.0

I’ve been working on a site that requires a random banner to be selected from a list of banners. In this case the banners needed to be both manageable via the WordPress Admin and contain whichever media type the client should see fit to use. One of the new features in WordPress 3 allows you to add custom post types, which means you can create a banner post type to use as required.

The first job is to register the new post type which is done in your theme’s functions.php file.

/*
* Add Banner Post Type
*/
function register_bannere_post_type() {
	$args = array(
		'label' => __('Banners'),
		'singular_label' => __('Banner'),
		'public' => true,
		'show_ui' => true,
		'capability_type' => 'post',
		'hierarchical' => false,
		'rewrite' => true,
		'supports' => array('title', 'editor'),
		'labels'=>array(
			'add_new_item'=>__('Add a New Banner'),
			'edit_item'=>__('Edit Banner'),
			'new_item'=>__('New Banner'),
			'view_item'=>__('View Banner'),
			'search_items'=>__('Search Banners'),
			'not_found'=>__('No Banners Found'),
			'not_found_in_trash'=>__('No Banners Found in Trash')
		)
	);
	register_post_type( 'banner' , $args );
}
add_action('init', 'register_banner_post_type');

So the next step is to create a couple of banner posts so you have some records to select from. Then you need a function to select and return a random entry from the available banner posts. The example below does just this and again should be places in your theme’s functions.php file.

/*
* return a randomly selected banner content string from available banners
*/
function get_random_banner(){

	// define scope
	global $wpdb;

	// count active features
	$intBannerCount = $wpdb->get_var( "
		SELECT count(*) record_count FROM {$wpdb->prefix}posts
		WHERE post_type = 'banner'
		AND post_status = 'publish';
	" );

	// logic checks
	if(!$intBannerCount)return false;

	// choose a random index
	$intRandomSelection = (int)(mt_rand(1,$intBannerCount)-1);

	// get the required record
	$intBannerId = $wpdb->get_var( "
		SELECT ID FROM {$wpdb->prefix}posts
		WHERE post_type = 'banner'
		AND post_status = 'publish'
		limit {$intRandomSelection},1;
	" );

	// load the post
	$post = get_post($intBannerId);

	// if we have results, pass back the filtered post content
	// without apply_filters html will not be valid
	return empty($post) ? false : apply_filters('the_content', $post->post_content);
}

Now all of the elements are in place, you have a custom post type, one or more banner posts in your database and the function to select and return a random entry. You can call the function anywhere in your theme but in most applications this is probably going to be either in header.php or sidebar.php.

echo get_random_banner();

And that’s it. You should now have a banner being displayed at random from your banner posts. Theres no limit to this kind of process with WordPress 3 and you can use the same method to store and display custom information in your build.

6 Comments

  1. Posted November 15, 2010 at 9:49 pm

    Great post! Is there anyway to have let’s say 3 banners on a page and have all three of them rotate?

  2. Posted November 23, 2010 at 8:28 pm

    Thanks Jenna, You could do this with custom posts. You would just need to display all 3 posts on the page then use a little css and jQuery to rotate them. There’s probably already a WordPress plugin for this so it might be worth taking a look at the plugins section on the website.

  3. Posted November 30, 2010 at 11:00 pm

    @Jenna if you want a rotating banner image using jQuery check out a really simple one on Jonathan Snooks site. This will create a flash like fade in/fade out effect.
    http://snook.ca/archives/javascript/simplest-jquery-slideshow

  4. ds123
    Posted July 5, 2011 at 4:13 am

    Hi John this is exactly what i was hoping to do …but i tried pasting the first part of your code into my functions.php and no banner type post shows up in the wordpress admin ..any idea why ? i tried a wordpress example custom post and that one worked though thanks!

  5. Posted July 5, 2011 at 10:17 pm

    Hi ds123, not sure to be honest. Feel free to post your code and ill take a look.

  6. Posted November 22, 2011 at 10:15 pm

    seems to be a pretty good solution to get a random post. thanks for posting!

Post a Comment

Your email is never shared. Required fields are marked *