How to make Bootstrap Carousel display WordPress Dynamic Content

When code from Twitter’s Bootstrap is not working, one of the main culprits is in linking the files up correctly. It seems to be especially common when adding Bootstrap javascript plugins to a WordPress theme. The Bootstrap files and your jquery library must be called in the proper sequence, along with loads of other scripts being called by other plugins you may be running. I’ve found the popular “WordPress Twitter Bootstrap CSS” plugin to be the best option so far, as it is quite painless and transparent. So Let’s begin.

1) Install ‘WordPress Twitter Bootstrap CSS’ Plugin

Of course you can do it manually, but this method takes 5 seconds, and you can be sure it loads the stylesheets and scripts in their proper places. Btw, it’s best to keep the default option of loading scripts in the footer. If you haven’t already, be sure to add the template tag <?php wp_footer();?> just before the </body> tag in the footer of your theme. The Bootstrap plugin will use this to load it’s necessary javascript.

2) Include the latest jquery library

I’ve added mine just above the wp_footer tag, like so…

[code]






[/code]

Now you can see that the jquery library is called first, and then the bootstrap stuff, as it should be.

3) Grab the Bootstrap Carousel source code

The demo lives here. And here is their source code…

[code]


[/code]

4) Verify your work so far

Before we start modifying this code, we’ll want to verify that the jquery library, the Bootstrap plugin files, and wordpress are all playing together nicely. Cut & Paste the above code into your own PHP template file, and do what you gotta do to view your carousel in a browser. I’ve saved mine as sidebar-carousel.php in my theme directory, so I can call it with <?php get_sidebar(‘carousel’);?> from inside my index.php template.
Just to save some time, I admit I already changed one thing in this code from the original- I added a height dimension to the images. Obviously the specific JPGs won’t show up, but the added height should allow you to see that the carousel is scrolling when right/left buttons are clicked.
Hint: If clicking a right/left button does nothing but add “#myCarousel” to your url, jquery is not linked up properly.

5) Prepare your Content

We’re keeping it as simple as posible here by creating a category named Home Slider and publishing 3 sample posts under that category. If you’ve already got plenty of content to play with, you can skip this step and insert your category of choice as category_name in the next step… you’ll see.

6) Add your first loop using WP_Query

Now that you’ve seen it work out of the box, it’s time to add the tricky part.
You’ll notice the source code provided 3 carousel items, i.e. <div class=”item”>. Our purposes only require 2: the 1st item with the added class “active”; and the 2nd item, which will self-replicate in the query loop we’re about to create. But first we’ll focus on the active carousel item.
We need to surround the <div class=”item active”> with its own WP_Query loop. So just above it, we ask for the latest post from the category Home Slider. Then we end that loop after the active item div with endwhile and the very important wp_reset_postdata fucntion.

[code]

Doug

Doug is an experienced project leader who strives to keep our clients' projects flowing smoothly. As a Developer, Doug is able to ensure a high level of customer satisfaction by focusing his efforts on the setup & support of content management systems (i.e. WordPress & Drupal), custom theme development, CSS/HTML coding, and graphic design. When Doug is not working on web projects, he can be found performing with several professional bands around San Diego.

75 thoughts to “How to make Bootstrap Carousel display WordPress Dynamic Content”

  1. About those right/left Carousel Controls…
    If your controls look really bizzarre, they may be inheriting an incompatible font from your theme.
    Rather than using images, Twitter designed their controls using CSS, which is Awesome, but the special characters they use for the arrows are subject to whatever font is being read. So this gives you control over the style of arrow, but beware that Georgia (and others, I’m sure) will print out some funkiness that first made me think the plugin itself was broken.

    1. Hey Doug,

      First of all–this is great. Thank you.

      Second of all, I have removed the OL “character-indicators” –the little dots at the bottom. But I would like to right a loop that counts the number of posts in my custom post type and then displays that number of indicators. Did you end up adding this functionality?

      Any help is much appreciated.

      Jed

  2. i tried this code and its worked for me.but whats my issue is that i cant find a motion from right to left as showed in your demo and its just changing from one image to another and so on…

    Any help on this issue?

  3. sirin k, your problem may be that you haven’t included bootstrap-transition.js which is needed for carousel to funtion properly.

    Doug, I have a question.. You have used ‘featured images’ attached to ‘posts in a certain category’ within your wordpress loop. This doesn’t seem like a perfect solution to me, I’d like to obtain the images from elsewhere.. Can you suggest an alternative please? Thanks in advance… Adam

    1. Absolutely. One solution would be to create a custom post type for the slideshow, and attach your images directly to that. I’m actually in the process of developing a 3rd option, which is to add a custom Carousel metabox to the post’s admin panel. This will appear when editing your post and give you the option to include it in the slideshow, and even add additional meta like a slide tagline (rather than using excerpt).

      I tried to keep things simple for this post, as you can imagine these alternatives can get pretty hairy. But no matter how complicated that part gets, the actual carousel markup should remain pretty clean & straight-forward, which is why I find it so appealing.
      Hope this gives you some ideas. And thanks for fielding that last question 🙂

  4. This is a great tutorial and it worked nicely. Thank you for this. Do you have a suggestion on how to place these rotating images in a specific order? Thanks in advance!

    1. You’re welcome! By default, they are ordered by the date of the post. You can try adding your own arguments to the queries, such as

      'orderby' => title

      .

  5. I’ve another solution to avoid repeating the loop twice. I don’t know if it’s the solution more nifty, but is my share.

    I prefer add one variable in the loop and set the class “active” with the ternary operator iff matches with the value 1.

    $i = 0;
    while ( $the_query->have_posts() ) : $i++;
    $active = ($i == 1) ? ‘ active’ : ”;

    Finally, I changed the HTML thus:

    <div class="item”>

    And that’s how I avoid putting the loop twice

    1. I’ve started performing the same idea using jQuery:
      [code]

  6. Thanks for sharing this, Doug! I’ve always wanted to understand how to add dynamic content (photos) to a slider in WP.

          1. I’ve also done it this way to target specific pages –
            [code]< ?php query_posts('post_type=page&post_id=18,19,20'); if(have_posts()): while(have_posts()): the_post();?>
            /* Your Code */
            < ?php endwhile; endif; wp_reset_query();?>[/code]
            – or this way to list page children –
            [code]< ?php query_posts('post_type=page&post_parent=18'); if(have_posts()): while(have_posts()): the_post();?>
            /* Your Code */
            < ?php endwhile; endif; wp_reset_query();?>[/code]

    1. Great Question! This had me deeply confused until just now.
      This bit of js is important:
      [code]<script type=”text/javascript”>
      jQuery(document).ready(function($) {
      $(‘.carousel’).carousel({
      interval: 1000
      })
      });
      </script>[/code]
      I added the interval option so you will see if it works right away.
      Be sure it is called after your Bootstrap js (which is called after your jQuery version). All my scripts are in my footer, so I appended this to the very end and it works great now.

  7. Aloha Doug!

    I have the problem that using the “the_post_thumbnail(‘large’)” function makes my bootstrap carousel not responsive anymore. Meaning the carousel re-sized, but not the picture inside it.

    Do you have a way to keep the responsiveness of the picture intact?

    Many thanks,
    Marco

  8. I wonder if it is possible to include a carousel showing the last posts on a category, but into a widget in the footer. Any ideas on how to make a widget perform php commands?

    1. I forget the precise name, but there is a plugin for a widget that performs php. You could try that, although the concept is often cited as a security risk. Another approach would be to put the carousel code into a separate php file & “include” or “require_once” from wherever you wish. And by this logic, you could create your own widget, which is too complex to instruct here. Perhaps that’s the next blog…

    1. Yeah, that’s the one. I’ve used it & it works great. But like I said, the concept of executing php from the wp backend is often cited as a security risk.

  9. Any ideas how one might get this to work using multiple items in a span4? I’m looking to query featured post images within several smaller spans. Meaning, I want to display 3 span4’s in 1 slide. Here’s what I have so far but it’s only showing one featured image in the first “active” slide.

    'Featured',
    'posts_per_page' => 1
    ));
    while ( $the_query->have_posts() ) :
    $the_query->the_post();
    ?>

    'Featured',
    'posts_per_page' => 3,
    'offset' => 1
    ));
    while ( $the_query->have_posts() ) :
    $the_query->the_post();
    ?>


  10. This is really nice, but I have troubles adding the same for widgets. So there is a div container that cycles thru the widgets from a sidebar. The widgets have to be in a scheme like: text-1, text-2 and so on, of course you want to display a link for every widget so it can be brought as active item to the front.
    This is where I fail, I can’t get a list of the Widget titles only inside the slideshow conatiner like:


    Widget1
    Widget2
    Widget3

  11. This code is really cool…
    But i´m having problems to display 2 posts per on each “page”. Only loads the first 2 last posts.

    I´ve set the 1st field, post_per_page = 2 , and the 2nd , post_per_page = 2 with a offset of 2 posts.

    When i configure with just 1 post per page it works fine.

    Anyone have a clue about what i´m doing wrong?

    ty

  12. I don’t want the excerpt and title to show on all of my slides. What’s the best way to handle this within this code?

  13. Brilliant work, just what I was looking for. Your tutorial was simple to follow and easy to implement. I love bootstrap for it’s flexibility and using it to customize wordpress has opened new doors for me as a designer.

  14. Hi,

    I would like to suggest another solution with only one wp_query.
    Generate HTML code and then catch first element with class ‘item’ and add class ‘active’ with jquery.

    My example would be something like:

    ‘Home Slider’,
    ‘posts_per_page’ => 5,
    ‘offset’ => 1
    ));
    while ( $the_query->have_posts() ) :
    $the_query->the_post();
    ?>

    jQuery(document).ready(function($) {
    $(‘.carousel .item:first:child’).addClass(‘active’);
    $(‘.carousel’).carousel({
    interval: 1000
    })
    });

  15. Hi,

    I would like to suggest another solution with only one wp_query.
    Generate HTML code and then catch first element with class ‘item’ and add class ‘active’ with jquery.

    My example would be something like:
    [code]
    ‘Home Slider’,
    ‘posts_per_page’ => 5,
    ‘offset’ => 1
    ));
    while ( $the_query->have_posts() ) :
    $the_query->the_post();
    ?>

    jQuery(document).ready(function($) {
    $(‘.carousel .item:first:child’).addClass(‘active’);
    $(‘.carousel’).carousel({
    interval: 1000
    })
    });

    [/code]

  16. Thanks for getting me in the right direction with this one. I needed a carousel on my homepage (I’m using Roots, so that gives me Bootstrap) and I found the Media Tags plugin to be a user-friendly solution to making this happen in combination with the following code (which I have in my page-home.php, but could go in any template if one wished to modularize it further). Rather than make “posts”, I used Media Tags to tag my carousel images with the tag “homepage”. I think this is the most editor-friendly solution short of a custom taxonomy. I offer it here in hopes it may help someone else, too:


    1)) {
    ?>

    $attachment_post) {
    $image_src = wp_get_attachment_image_src($attachment_post->ID, 'large');
    ?>
    <div class="item ">
    <img src="" />

    post_title; ?>

    post_excerpt;?>



  17. Hello
    Thanks for the excellent code… works perfect for my project.

    But i need some help.. I just need to post one carousel-caption for my carousel.. How can I make that?

    thanks

  18. Thank you for the code, it works wonders. My problem is that it does not loop continuously at the end of the last slide. What can I change to for it to play continuously?

  19. Hello! anyone know how to put image on the carousel?.. All i see in only the post and the title and excerpt..

  20. Hi,
    This is a great tutorial but WordPress Twitter Bootstrap CSS’ Plugin not work for me. How I I can find the css code for this tutorial?
    Thanks!

  21. Hi guys am new to WP,

    Just alittle confused on who the image is getting called in the php go the slider working with a stactic image in the php but cant seem to get the image pulling dynamically can anyone help please

Leave a Reply

Your email address will not be published. Required fields are marked *