Advertisement
  1. Code
  2. JavaScript
  3. jQuery

Adding a Responsive jQuery Slider to Your WordPress Theme

Scroll to top
Read Time: 10 min

Today I'm going to take you through integrating a responsive jQuery slider into your WordPress theme or site. It's not a groundbreaking tutorial but it's one that's rarely done right, so I'd like to try and fix that. In this tutorial we're going to cover every step from creating a custom post type to hold our slides, to actually using the slider within our site.

We're going to be using the lovely FlexSlider 2 by WooThemes as it's a very well-coded responsive slider that's licensed under the GPLv2 License. If you're interested, you can take a look at the code for FlexSlider in its GitHub Repository.

Before we do anything, we're going to take a step back and think about:

  • What files the slider requires
  • What files we require

The first thing we're going to do is download FlexSlider.

After you've done that, go ahead an unzip it.

There are a few files there we're interested in, mainly:

  • flexslider.css
  • images/bg_direction_nav.png
  • jquery.flexslider-min.js

They're all we really need from the FlexSlider download.

Step 1 Setting Up the Files

Let's move those 3 files from the above into our theme's directory now. Depending on your theme or set-up you can place the files wherever you'd like, just take note of where those files are sourced/referenced and adjust the code to fit their new location.

For the sake of this tutorial, we'll be using the default Twenty Eleven theme. In the inc/ directory, create a new folder called slider. In there, let's create a few folders:

  • css
  • images
  • js

Let's put flexslider.css in the css folder, bg_direction_nav.png in the images folder and jquery.flexslider-min.js in the, you guessed it, js folder.

Note: Normally I would place these in css/images/js folders throughout the theme's directory with other files but in order to make this tutorial 'universal', we're organising our files this way. If you're experienced with WordPress theme development you may want to manually organise your files.

Now we're going to create 2 more files in the slider folder:

  • slider.php - creates the slider's template & loads the slider's files
  • slider_post_type.php - creates the slider post type

You should now have a slider folder that looks something like this:

Before we go ahead, open up your functions.php file and add in the following two lines, which will load the two .php files we just created:

1
// Create Slider Post Type

2
require( get_template_directory() . '/inc/slider/slider_post_type.php' );
3
// Create Slider

4
require( get_template_directory() . '/inc/slider/slider.php' );

Now... let's start coding!

Step 2 Slider Post Type

First thing we're going to do is create a custom post type that will hold all our slides. Custom Post Types were introduced in WordPress 3.0 and are probably the coolest thing to ever happen to the world (too far? I just love them).

Open up slider_post_type.php and add the following code to create the slide custom post type:

1
<?php
2
3
// Create Custom Post Type

4
	
5
	function register_slides_posttype() {
6
		$labels = array(
7
			'name' 				=> _x( 'Slides', 'post type general name' ),
8
			'singular_name'		=> _x( 'Slide', 'post type singular name' ),
9
			'add_new' 			=> __( 'Add New Slide' ),
10
			'add_new_item' 		=> __( 'Add New Slide' ),
11
			'edit_item' 		=> __( 'Edit Slide' ),
12
			'new_item' 			=> __( 'New Slide' ),
13
			'view_item' 		=> __( 'View Slide' ),
14
			'search_items' 		=> __( 'Search Slides' ),
15
			'not_found' 		=> __( 'Slide' ),
16
			'not_found_in_trash'=> __( 'Slide' ),
17
			'parent_item_colon' => __( 'Slide' ),
18
			'menu_name'			=> __( 'Slides' )
19
		);
20
21
		$taxonomies = array();
22
23
		$supports = array('title','thumbnail');
24
25
		$post_type_args = array(
26
			'labels' 			=> $labels,
27
			'singular_label' 	=> __('Slide'),
28
			'public' 			=> true,
29
			'show_ui' 			=> true,
30
			'publicly_queryable'=> true,
31
			'query_var'			=> true,
32
			'capability_type' 	=> 'post',
33
			'has_archive' 		=> false,
34
			'hierarchical' 		=> false,
35
			'rewrite' 			=> array( 'slug' => 'slides', 'with_front' => false ),
36
			'supports' 			=> $supports,
37
			'menu_position' 	=> 27, // Where it is in the menu. Change to 6 and it's below posts. 11 and it's below media, etc.

38
			'menu_icon' 		=> get_template_directory_uri() . '/inc/slider/images/icon.png',
39
			'taxonomies'		=> $taxonomies
40
		);
41
		register_post_type('slides',$post_type_args);
42
	}
43
	add_action('init', 'register_slides_posttype');

Custom Post Type added! Below that we'll add the metabox where there's a field for the URL that the slide should link to. We're now going to copy the following big wall of code:

1
// Meta Box for Slider URL

2
	
3
	$slidelink_2_metabox = array( 
4
		'id' => 'slidelink',
5
		'title' => 'Slide Link',
6
		'page' => array('slides'),
7
		'context' => 'normal',
8
		'priority' => 'default',
9
		'fields' => array(
10
	
11
					
12
					array(
13
						'name' 			=> 'Slide URL',
14
						'desc' 			=> '',
15
						'id' 				=> 'wptuts_slideurl',
16
						'class' 			=> 'wptuts_slideurl',
17
						'type' 			=> 'text',
18
						'rich_editor' 	=> 0,			
19
						'max' 			=> 0				
20
					),
21
					)
22
	);			
23
				
24
	add_action('admin_menu', 'wptuts_add_slidelink_2_meta_box');
25
	function wptuts_add_slidelink_2_meta_box() {
26
	
27
		global $slidelink_2_metabox;		
28
	
29
		foreach($slidelink_2_metabox['page'] as $page) {
30
			add_meta_box($slidelink_2_metabox['id'], $slidelink_2_metabox['title'], 'wptuts_show_slidelink_2_box', $page, 'normal', 'default', $slidelink_2_metabox);
31
		}
32
	}
33
	
34
	// function to show meta boxes

35
	function wptuts_show_slidelink_2_box()	{
36
		global $post;
37
		global $slidelink_2_metabox;
38
		global $wptuts_prefix;
39
		global $wp_version;
40
		
41
		// Use nonce for verification

42
		echo '<input type="hidden" name="wptuts_slidelink_2_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';
43
		
44
		echo '<table class="form-table">';
45
	
46
		foreach ($slidelink_2_metabox['fields'] as $field) {
47
			// get current post meta data

48
	
49
			$meta = get_post_meta($post->ID, $field['id'], true);
50
			
51
			echo '<tr>',
52
					'<th style="width:20%"><label for="', $field['id'], '">', stripslashes($field['name']), '</label></th>',
53
					'<td class="wptuts_field_type_' . str_replace(' ', '_', $field['type']) . '">';
54
			switch ($field['type']) {
55
				case 'text':
56
					echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" /><br/>', '', stripslashes($field['desc']);
57
					break;
58
			}
59
			echo    '<td>',
60
				'</tr>';
61
		}
62
		
63
		echo '</table>';
64
	}	
65
	
66
	// Save data from meta box

67
	add_action('save_post', 'wptuts_slidelink_2_save');
68
	function wptuts_slidelink_2_save($post_id) {
69
		global $post;
70
		global $slidelink_2_metabox;
71
		
72
		// verify nonce

73
		if (!wp_verify_nonce($_POST['wptuts_slidelink_2_meta_box_nonce'], basename(__FILE__))) {
74
			return $post_id;
75
		}
76
	
77
		// check autosave

78
		if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
79
			return $post_id;
80
		}
81
	
82
		// check permissions

83
		if ('page' == $_POST['post_type']) {
84
			if (!current_user_can('edit_page', $post_id)) {
85
				return $post_id;
86
			}
87
		} elseif (!current_user_can('edit_post', $post_id)) {
88
			return $post_id;
89
		}
90
		
91
		foreach ($slidelink_2_metabox['fields'] as $field) {
92
		
93
			$old = get_post_meta($post_id, $field['id'], true);
94
			$new = $_POST[$field['id']];
95
			
96
			if ($new && $new != $old) {
97
				if($field['type'] == 'date') {
98
					$new = wptuts_format_date($new);
99
					update_post_meta($post_id, $field['id'], $new);
100
				} else {
101
					if(is_string($new)) {
102
						$new = $new;
103
					} 
104
					update_post_meta($post_id, $field['id'], $new);
105
					
106
					
107
				}
108
			} elseif ('' == $new && $old) {
109
				delete_post_meta($post_id, $field['id'], $old);
110
			}
111
		}
112
	}

Phew. That's over. Go to your Dashboard and you'll see a new shiny 'Slides' Custom Post Type.

Step 3 Load Slider Files

Open up slider.php. Now we're going to enqueue jQuery, the FlexSlider jQuery script and the FlexSlider stylesheet. Alternatively you could copy the code from flexslider.css to your style.css file if desired.

1
<?php
2
3
// Enqueue Flexslider Files

4
5
	function wptuts_slider_scripts() {
6
		wp_enqueue_script( 'jquery' );
7
8
		wp_enqueue_style( 'flex-style', get_template_directory_uri() . '/inc/slider/css/flexslider.css' );
9
10
		wp_enqueue_script( 'flex-script', get_template_directory_uri() .  '/inc/slider/js/jquery.flexslider-min.js', array( 'jquery' ), false, true );
11
	}
12
	add_action( 'wp_enqueue_scripts', 'wptuts_slider_scripts' );

While we're doing this, there's something you need to do. Due to our file structure, the flexslider.css needs some editing so it knows where to find the arrow image. Open it up and do a search and replace for:

  • images with ../images

Step 4 Initialize Slider

Now we need to add some jQuery to our <head> in order to initialize the slider. Let's add in the following lines to slider.php below the code we just added!

1
// Initialize Slider
2
3
	function wptuts_slider_initialize() { ?>
4
		<script type="text/javascript" charset="utf-8">
5
			jQuery(window).load(function() {
6
				jQuery('.flexslider').flexslider({
7
					animation: "fade",
8
					direction: "horizontal",
9
					slideshowSpeed: 7000,
10
					animationSpeed: 600
11
				});
12
			});
13
		</script>
14
	<?php }
15
	add_action( 'wp_head', 'wptuts_slider_initialize' );

One of the reasons I chose to use FlexSlider is because of its flexability. There are quite a few parameters you can tinker with, but I just included four important ones above. Try changing slide to fade, or horizontal to vertical. You can take a look at all of the paremeters over here.

Note: Keep in mind that another way to do the above is using the wp_localize_script function (see in Codex) but this is a little bit advanced for this tutorial. However, Pippin Williamson (another Wptuts+ author) has just written an excellent tutorial on the subject if you're interested.

Step 5 Create Slider

Now we're going to actually create the template for the slider. First, we'll do a WP_Query to pull 'posts' from the Slides Custom Post Type. Next, we'll check for slides and if so start the slider. We'll then start the loop. Each 'slide' will then check if a slide URL has been set and if so, create a link for it. The slide's image will then be displayed and the loop will be closed up.

1
// Create Slider

2
3
	function wptuts_slider_template() {
4
5
		// Query Arguments

6
		$args = array(
7
			'post_type' => 'slides',
8
			'posts_per_page' => 5
9
		);	
10
11
		// The Query

12
		$the_query = new WP_Query( $args );
13
14
		// Check if the Query returns any posts

15
		if ( $the_query->have_posts() ) {
16
17
			// Start the Slider ?>

18
			<div class="flexslider">
19
				<ul class="slides">
20
21
					<?php
22
					// The Loop

23
					while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
24
						<li>
25
26
						<?php // Check if there's a Slide URL given and if so let's a link to it

27
						if ( get_post_meta( get_the_id(), 'wptuts_slideurl', true) != '' ) { ?>
28
							<a href="<?php echo esc_url( get_post_meta( get_the_id(), 'wptuts_slideurl', true) ); ?>">
29
						<?php }
30
31
						// The Slide's Image

32
						echo the_post_thumbnail();
33
34
						// Close off the Slide's Link if there is one

35
						if ( get_post_meta( get_the_id(), 'wptuts_slideurl', true) != '' ) { ?>
36
							</a>
37
						<?php } ?>
38
39
					    </li>
40
					<?php endwhile; ?>
41
42
				</ul><!-- .slides -->
43
			</div><!-- .flexslider -->
44
45
		<?php }
46
47
		// Reset Post Data

48
		wp_reset_postdata();
49
	}

Step 6 Using the Slider

Well, we've finally made the slider! Now it's time to actually use it. You can open up any template file, such as index.php, and echo the wptuts_slider_template function to display the slider.

So if we wanted to show the slider in Twenty Eleven right after the header on the home page, we would open up index.php and just beneath get_header(); ?>, add the following:

1
<?php echo wptuts_slider_template(); ?>

But what if you're making this for a client or someone who just doesn't want to touch template files and PHP? We should probably create a shortcode for them, so they can just use the slider with a [slider] shortcode.

Add this at the bottom of slider.php:

1
// Slider Shortcode

2
3
	function wptuts_slider_shortcode() {
4
		ob_start();
5
		wptuts_slider_template();
6
		$slider = ob_get_clean();
7
		return $slider;
8
	}
9
	add_shortcode( 'slider', 'wptuts_slider_shortcode' );

The slider can now be used within posts, pages or anywhere else that accepts a shortcode!

Download

If you'd like, you can download the slider folder, which contains everything we went through in this tutorial. You just need to drop it in your theme's inc folder (or somewhere else is fine, but be sure to adjust the code below) and add the following to your functions.php:

1
// Create Slider Post Type

2
require( get_template_directory() . '/inc/slider/slider_post_type.php' );
3
// Create Slider

4
require( get_template_directory() . '/inc/slider/slider.php' );

Note: For the sake of this tutorial, the namespace/text domain wptuts has been used. You should do a search and replace on all code if you're just copying/pasting it and replace:

  • wptuts_ with yourname_
  • 'wptuts' with 'yourname'

If you liked this tutorial, let me know and I'll continue with a tutorial on customising our slider! We'll then take a look at using thumbnails for navigation, integrating video slides and adding in captions.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.