Custom content slider for your WordPress theme is bliss!

As we have seen, there are a lot of WordPress content sliders available as a plugin. Some of them are very useful and having very good visuals. While developing theme for WrapCode.com I needed a lightweight, flexible content slider. I looked almost every anticipated slider out there on the Internet but somehow I was little disappointed by all of them. Then I found one very beautiful, lightweight, super flexible and configurable slider, bxSlider. bxSlider is jQuery content slider which makes use of simple HTML tags like UL (unordered list) or div.

Some features of bxSlider as given on the official website –

  • Horizontal, vertical, and fade transitions
  • Display and move multiple slides at once (carousel)
  • Prev / next, pager, auto controls
  • Easing transitions
  • Random start
  • Ticker mode
  • Before, after, first, last, next, prev callback functions
  • Optional styling included
  • Tons of options

If you want to display static content on HTML or PHP page, you can refer official website. It is very easy to implement and configurable too.

Implement bxSlider to display WordPress Content (Posts)

Download bxSlider JQuery Package
  1. Go to www.bxslider.com and download the package.
  2. Copy jquery.bxSlider.min.js to /wp-cotent/themes/theme_name/js
  3. Copy bx_styles.css and images to /wp-cotent/themes/theme_name/css
  4. [Skip Easing script if already present] Copy jquery.easing.1.3.js to  /wp-cotent/themes/theme_name/js
Register and Enqueue JS and CSS

Enqueuing javascript and stylesheet is safe, recommended method and considered as best practice as well. To know more about enqueing scripts and stylesheet you can refer (http://codex.wordpress.org/Function_Reference/wp_enqueue_script) and (http://codex.wordpress.org/Function_Reference/wp_enqueue_style)

I assume you areamiliar with both the functions now. To enqueue a script or a stylesheet you will have to write a function. If you want to be a successful WordPress theme developer, always remember to write functions in a separate file called functions.php. You can open and edit functions.php in several ways such as using WordPress. Editor (Appearance -> Editor), FTP Client (CuteFTP) or File Manager present in your Web Hosting Control Panel.

Write a new function in functions.php

function bxslider{
	wp_register_script('bxslider', get_bloginfo('template_directory').'/js/jquery.bxSlider.min.js');
	wp_enqueue_script('bxslider');
        wp_register_script('easing', get_bloginfo('template_directory').'/js/ jquery.easing.1.3.js ');
	wp_enqueue_script('easing');
	wp_register_style('bxslider-style', get_bloginfo('template_directory').'/css/bx_styles.css');
	wp_enqueue_style('bxslider-style');
}
add_action('init', 'bxslider');
Make sure you have triggered JQuery

Make sure you enqueue JQuery. Either write another function in functions.php or enqueue it in header.

function load_jquery() {
	if (!is_admin()) {
	wp_enqueue_script('jquery');
	}
}
add_action('init', 'load_jquery');
Writing a custom Javascript that controls bxSlider

Enqueing Javascripts and Stylesheet isn’t everything. We have to write a function that controls behaviour of bxSlider. I have written a sample code below (I am using the same code for slider present on my blog’s homepage.). Speaking honestly, writing a code in header.php is not at all a good practice. You should write it in custom javascript and then register and enqueue it using enqueue functions (Read Register and Enqueue JS and CSS  section above).

Open header.php, paste following code just before closing </head> tag.

<script type=”text/javascript”>
	jQuery(document).ready(function(){
		jQuery(‘#bxslider’).bxSlider({
			easing: ‘swing’,
			auto:true,
			pause:5000,
		});
	});
</script>

WARNING : Make sure <?php wp_head(); ?> is present in header.php, absence of the same can break many plugins.

Adding the actual slider in homepage

Since we are working on a content slider, we have to write a code that fetches WordPress content such as post title, category, excerpt / content etc. Chosing the right content is your choice. I will write a code for slider that contains post title, thumbnail, excerpt and permalink.

Before looking at the actual wordpress functions that triggers queries to fetch data from database, let’s take a look at the simple code that illustrates content of slider.

<ul id="slider1">
	<li>Slide one content</li>
	<li>Slide two content</li>
	<li>Slide three content</li>
	<li>And so on...</li>
</ul>

or

<div id="slider1">
  <div>Slide one content</div>
  <div>Slide two content</div>
  <div>Slide three content</div>
  <div>And so on...</div>
</div>

Now, our aim is to convert either any one of the above code into the code that displays WordPress content. I am going to use unordered list for the same (ul, li)

Some cosmetics (Slider Layout)

We have enqueued bxSlider’s CSS which will take care of almost everything in terms of styling and positioning. Take a look at how slider will look.

The slider layout is divided in following classes –
  1. bxslider : The wrapper or parent container
  2. thumbnail : thumbnail container
  3. content : post content container
  4. content title (will be styled as h2 or h3 or similar thing)
  5. content excerpt (within a paragraph)

Here’s the sample CSS :

#slider{
	width:624px; /*defines width*/
	/*any other styling such as background, border, shadow etc. */
}

.thumbnail{
	float:left;
	width:265px;
	height:170px;
	border-radius:5px;
	overflow:hidden;
}

.content{
	float:right;
	/*Other properties of your choice*/
}

.content h2{
	font-size:20px;
	line-height:28px;
	/*Other properties of your choice*/
}

.content p{
	font-size:12px;
	line-height:20px;
	/*Other properties of your choice*/
}
Slider and The Loop

The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post.

Enough introduction, the loop actually displays all the posts, here’s the syntax of The Loop

//Start of the loop
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
	//THE CODE GOES HERE
<?php endwhile; else: ?>
	<p><?php _e(‘Sorry, no posts matched your criteria.’); ?></p>
<?php endif; ?> //End of the Loop

Learn more about The Loop and Various examples from Here

Slider and the Loop – Part II

Now, let’s put all the ingredients together and cook something tasty. As we know the loop displays all the posts present in database one by one. All we need to do is put each individual post content in to the list item  <li> THE CODE HERE </li>

<ul id="bxslider">
		<?php if( have_posts() ) : while( have_posts() ) : the_post(); ?>
		<!--Each post is wrapped in List item..	-->
		<li>
			<div class="thumbnail">
				<?php
				if(has_post_thumbnail()) { ?>
				<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_post_thumbnail( 'thumbnail');?></a> <!-- Image links to Post -->
				<?php } else { ?>
					<div class="no-thumb"><h2>No thumbnail for this :D</h2><h3>wrapcode</h3></div>
				<?php }
				?>
			</div>
			<div class="content">
				<a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>">
					<h2>
						<?php the_title(); ?>  <!-- The Title -->
					</h2>
				</a>
				<p>
				<?php
                                   the_excerpt();
				?>
				</p>
		</div>
		</li> <!-- END OF LIST ITEM -->
		<?php endwhile; endif;?>
		<?php wp_reset_query();?>
</ul>
Functions explained
  1. has_post_thumbnail() : Checks if post has thumbnail
  2. php_the_title(); – Returns Post title
  3. the_post_thumbnail(‘thumbnail’); – returns thumbnail image
  4. the_excerpt(); – Displays excerpt of post
Demo

See slider in action here -> WrapCode

Conclusion

I hope you have learned how to include content slider in your theme manually. Though there are many plug ins available, you should look for manual ways if you really want to be a good developer. I have kept this post open for comments. I would love to hear your responses and suggestions.

  • Joseph

    Thank you so much for very helpful post. It made my day! 😀 Cheers <3

    Good website design, very simple yet beautiful!

    • >NJさんコメントありがとうございます。loop.phpの120行目あたりから<?php /* How to display all other posts. */ ?><?php else : ?><div id=”post-<?php the_ID(); ?>” <?php post_class(); ?>> <a href=”<?php the_permalink() ?>” rel=”bookmark” title=”<?php pritnf(__(‘Permanent Link to %s’, ‘kubrick’), the_title_attribute(‘echo=0’)); ?>” class=”thumbnail_img”><?php the_post_thumbnail(‘thumbnail’); ?></a><h2 class=”time”><?php the_time(__(‘Y年n月j日(D)’)) ?> <!– by <?php the_author() ?> –></h2><h2 class=”entry-title”><a href=”<?php the_permalink(); ?>” title=”<?php pritnf( esc_attr__( ‘Permalink to %s’, ‘twentyten’ ), the_title_attribute( ‘echo=0’ ) ); ?>” rel=”bookmark”><?php the_title(); ?></a></h2><div class=”entry-meta”>という感じで表示したい部分にを記入しています。

      • Can you elaborate your comment in detail please?

  • Thanks So much very amazing helpful tutorial. thanks again for such a nice tutorial and for nice words

  • Pingback: Top 160 Tutoriais WordPress – incluindo Basico, Desenvolvimento e Plugins – Site para Empresas – Blog sobre Internet e Criação de Site()

  • Zac

    When I add the functions into my functions.php, my admin area goes blank and I have to re-upload my functions.php. Are you double triple sure it’s correct?

    • I am double triple sure, the function is correct. Make sure all the functions are closed properly.

      • Actually Rahul your function is wrong. it should start:

        function bxslider() {

        Try double, triple checking it next time! Hope this helps you Zac.

  • Is it possible to pull a WordPress.com blog in to a Joomla Site with this PHP code via iframe? For example since I do not have access to a wordpress.com blog – wordpress hosted, would this still work?

  • Pingback: Wordpress Top 160 Tutoriais | Blog do Dinheiro Brazil()

  • Pingback: รวมสุดยอดสอนแต่ง WordPress ขั้นเทพ | HopeApps.com()

  • This is a better tutorial than the other tutorials available on the net. Thanks rahul for this tutorial.

  • m88

    I think the admin of this website is actually working hard in favor of his web site, for the
    reason that here every data is quality based stuff.

  • Stan

    Hi, thanks for the great article! Just curious do we need a to load a version of jquery 1.8.2 to support bxslider? Is this the wordpress default jquery you are triggering?

    function load_jquery() {
    if (!is_admin()) {
    wp_enqueue_script(‘jquery’);
    }
    }
    add_action(‘init’, ‘load_jquery’);

  • hemchand

    This is nice tutorial.