This tutorial discusses the usage of the carousel component included with the Bootstrap CSS Framework in your WordPress theme. I’ll present and explain code that generates the Bootstrap slider for your WordPress theme – we’ll be developing on top of what we created in the previous tutorial which discussed creation of WordPress themes from scratch using the Bootstrap framework.
If you’d rather download the source code for this tutorial right away, here you go: Download Source
Some Thoughts on Sliders
If you’re developing a WordPress theme, you’re most likely including a slider on the home page for the user to set up and customize. All the latest and greatest themes include at least one, if not multiple, slideshow options. Sliders or carousels help showcase key content in an engaging and interactive way and highlight some of the main areas of your work or ideas.
However, the case against sliders is also pretty strong as you can read here, here and here. The Bootstrap framework includes a basic but useful carousel that is lightweight and easy to set up. Integrating a slider into your theme is quite simple, but there are many different ways this can be done.
Since a slider consists of multiple slide items that rotate at a given speed, transitioning with specific effects, developers are often tempted to include “Slides” as a Custom Post Type. That way, a user can create as many slides as needed, with each slide item manageable through the WordPress backend under its own “Slides” menu or page.
There is also a growing trend to include the slides as items in the theme Customize section. Themes provide a pre-determined and large enough set of fields which create a front end slider when properly filled out. This includes putting fields such as text boxes for slide captions, text areas for slide descriptions, image upload for the slide image itself – for each slide item. This kind of creates a pseudo custom post type and the theme options end up storing the data for the slide ‘type’. This approach violates the principle that “themes are meant to present content, not create content.”
According to the WordPress.org theme requirements, custom post types (pseudo or otherwise) are not allowed. Themes are restricted to presenting content and if any of the above two approaches are used by theme authors, the carousels are asked to be removed or amended to conform to the requirements.
Many premium themes authors make their themes compatible with popular slider plugins such as Slider Revolution, Layer Slider, etc. That way, slide creation and management stays within the plugin realm and the themes integrate with the plugins to incorporate the carousels.
For the purpose of this tutorial, lets take a simple but effective approach to creating a Bootstrap slider for your WordPress theme. We are going to automatically generate a carousel based on the featured images of the five most recent posts that are tagged with the word “slide”.
Getting Started
So here is what we need to do:
- Figure out where to include the slider in our base theme
- Write code to fetch the posts that will form the slideshow
- Integrate with Bootstrap code so that the slider posts (fetched in the step above) show up as a Bootstrap Carousel
Looking at the front end of the theme we’ve been developing in the previous articles (part 1, part 2), lets add the carousel right under the blog name and description and above the blog feed and sidebar.
Fetch “Slider” Posts
Since we’re going to create the slider using the 5 most recent posts tagged with the word “slide”, we need to execute a custom query using WP_Query. Do read up on WP_Query; I am not going into too much detail – it is an extensive topic for another day. We need posts associated with certain tags – details of how WP_Query allows us to do this can be explored here. Here is a simple summary loop that we will be incorporating in our slider code:
$args = array( 'tag' => 'slide', 'nopaging'=>true, 'posts_per_page'=>5 ); $slider_query = new WP_Query( $args ); if ( $slider_query->have_posts() ) { while ( $slider_query->have_posts() ) { $slider_query->the_post(); /* collect slides here */ } } wp_reset_postdata();
Lets take the above block of code apart!
As you can see, WP_Query takes a set of arguments that can be used to tell it about the kind of posts we’re looking for. There are a whole lot of possible arguments that it takes; we’re only concerned with the 5 most recent posts tagged with “slide” for now. The $args array variable defines the relevant arguments needed here: we want the tag to be ‘slide’, no pagination necessary, and 5 posts per page. The posts are ordered by latest first by default so we’re not explicitly specifying any “order by” parameters.
If the query returns any posts, which we check by using the function have_posts(), we iterate through the posts by using the_post().
Okay so that is the foundation on which we will proceed with our integration with the Bootstrap carousel HTML code.
Edit functions.php
If you’re using the code we ended up with in the previous tutorial, we need to make an edit in the functions.php file to add support for featured images. Add this line in the bootstrapstarter_wp_setup() function – so it becomes:
function bootstrapstarter_wp_setup() { add_theme_support( 'title-tag' ); add_theme_support( 'post-thumbnails' ); } add_action( 'after_setup_theme', 'bootstrapstarter_wp_setup' );
Without this line, you will not see the “Featured Image” section on the post edit screen.
Edit header.php
Now based on the diagram above, we need to insert the slider code under the header area but above the blog feed and sidebar content. Edit header.php and add a call to get_template_part() to include the file that will be housing our carousel code:
<div class="blog-header"> <h1 class="blog-title"><?php bloginfo( 'name' ); ?></h1> <?php $description = get_bloginfo( 'description', 'display' ); ?> <?php if($description) { ?><p class="lead blog-description"><?php echo $description ?></p><?php } ?> </div> <?php get_template_part('parts/slider'); ?> <div class="row">
I am a big fan of segmenting and compartmentalizing code into files and functions. Separating the entire slider logic into a separate file that can be called using get_template_part() makes the code easy to manage and modify later on. The get_template_part() function also makes it easy for a theme to reuse sections of code in a easy to overload way for child themes.
Create parts/slider.php
Now lets create the new file called slider.php and save it in a new folder called “parts”. All the partial components of our theme will reside in this folder “parts”.
<?php $slides = array(); $args = array( 'tag' => 'slide', 'nopaging'=>true, 'posts_per_page'=>5 ); $slider_query = new WP_Query( $args ); if ( $slider_query->have_posts() ) { while ( $slider_query->have_posts() ) { $slider_query->the_post(); if(has_post_thumbnail()){ $temp = array(); $thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'full', true); $thumb_url = $thumb_url_array[0]; $temp['title'] = get_the_title(); $temp['excerpt'] = get_the_excerpt(); $temp['image'] = $thumb_url; $slides[] = $temp; } } } wp_reset_postdata(); ?> <?php if(count($slides) > 0) { ?> <div id="carousel-example-generic" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <?php for($i=0;$i<count($slides);$i++) { ?> <li data-target="#carousel-example-generic" data-slide-to="<?php echo $i ?>" <?php if($i==0) { ?>class="active"<?php } ?>></li> <?php } ?> </ol> <div class="carousel-inner" role="listbox"> <?php $i=0; foreach($slides as $slide) { extract($slide); ?> <div class="item <?php if($i == 0) { ?>active<?php } ?>"> <img src="<?php echo $image ?>" alt="<?php echo esc_attr($title); ?>"> <div class="carousel-caption"><h3><?php echo $title; ?></h3><p><?php echo $excerpt; ?></p></div> </div> <?php $i++; } ?> </div> <a class="left carousel-control" target="_blank" href="#carousel-example-generic" role="button" data-slide="prev"><span class="glyphicon glyphicon-chevron-left" aria-hidden="true"></span><span class="sr-only">Previous</span></a> <a class="right carousel-control" target="_blank" href="#carousel-example-generic" role="button" data-slide="next"><span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span><span class="sr-only">Next</span></a> </div>
Here is what we’re doing in the code above: we run a query to find 5 most recent posts tagged with “slide”, and store the title, excerpt, and featured image URL (full size) in an array for later use. Here is the code to fetch the absolute URL of the featured image of a post:
$thumb_id = get_post_thumbnail_id(); $thumb_url_array = wp_get_attachment_image_src($thumb_id, 'full', true); $thumb_url = $thumb_url_array[0];
Once we have the array of slides, we use it to generate the carousel code. Please note, the “active” class needs to be added to one of the slides. Otherwise, the carousel will not be visible. We’ve added it to the first slide by checking if $i is zero.
Test The Code
Add a few posts with the tag “slide”. Don’t forget to upload some featured images for each of them. Now go to the front end and you should see something like this.
There you have it – pure, clean, and simple. Here are some thoughts on expanding on this code for your project:
- Specify a thumbnail size (in functions.php) corresponding to the ideal slide image size based on your design. Fetch this custom thumbnail size while creating the slider. In the code above, we’re simply fetching the full size image uploaded for the posts.
- Give the user control over the tag for the slider posts. Right now, we’ve hard coded the tag “slide” into the theme code. We can allow the user to select the tag(s) to use for the slider in the theme options (Customize screen). That makes this more flexible and user friendly.
- Create a shortcode to generate the slider so it can be used within widgets, posts and pages content.
- Alternatively, you can have the user select a category (instead of a tag) from which to select posts for the slider.
- For more control, give the user a choice of up to 5 select fields containing a list of all posts. That way, the user can select exactly which posts show up in the carousel and in which order.
Download the source here: Download Source