Try Tuts+ Premium, Get Cash Back!
Displaying Posts in a Carousel

Displaying Posts in a Carousel

Tutorial Details
  • Program: WordPress
  • Version: 3.1+
  • Difficulty: Intermediate
  • Estimated Completion Time: 1-2 hours

Having a recent posts carousel on your blog is a great way to make it more interactive for your visitors.

Recently I had a client ask me to make a recent posts carousel for their website. I said yeah sure, thinking there must be some kind of plugin I can find to do just that real quick. Boy was I wrong. I spent a long time trying to find one and the ones I found didn’t do what I wanted at all. I figured, with all this time wasting, I’ll just make one myself. Just gotta find a good base code. So that’s when I came upon carouFredSel. Here’s the link: http://caroufredsel.frebsite.nl/. I loved their examples and though it still didn’t do everything I wanted, like show a caption below the image, the functionality was exactly what I needed. So long story short, here are the details.


Step 1 Download carouFredSel

Alright, let’s start by going to http://caroufredsel.frebsite.nl/ and downloading the carousel code and copying the jquery.carouFredSel-5.5.0-packed.js file to your WordPress theme folder.


Step 2 Edit Your functions.php File

Next up, open up your functions.php file and add this little bit of code:

if ( function_exists( 'add_image_size' ) ) { 
	add_image_size( 'sliderimg', 200, 150, true );
}

Be sure to replace the 200 and 150 with your own dimensions. Save it and upload the file. After you upload it, in your post sidebar you’ll see a new option titled “Featured Image“. You can upload any image you want to use here and this will be the image that will display in the carousel. Also note that we’re calling it “sliderimg“. I’ll tell you why soon.


Step 3 Initialising carouFredSel and more for Your functions.php File

Make a new JavaScript file called wptuts-caroufredsel.js and put the following code inside, then copy it into your WordPress theme folder:

jQuery(function($) {
	$('#foo2').carouFredSel({
		prev: '#prev2',
		next: '#next2',
		auto: false,
		items: 3,
	});
});

Here is something else to take note of for later. #foo2 – this will be the id of the carousel we’ll be using. We’ll need this so we can style it in CSS. Also note the #prev2 and #next2 id’s for styling the previous and next buttons and lastly, the number 3 is how many items you want to show at a time. In this case it’s 3.

Now, open your functions.php file again and add the following code to load the JavaScript files:

function wptuts_load_caroufredsel() {
	// Enqueue carouFredSel, note that we specify 'jquery' as a dependency, and we set 'true' for loading in the footer:
	wp_register_script( 'caroufredsel', get_template_directory_uri() . '/js/jquery.carouFredSel-5.5.0-packed.js', array( 'jquery' ), '5.5.0', true );

	// For either a plugin or a theme, you can then enqueue the script:
	wp_enqueue_script( 'wptuts-caroufredsel', get_template_directory_uri() . '/js/wptuts-caroufredsel.js', array( 'caroufredsel' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'wptuts_load_caroufredsel' );

Make sure to change the paths to wherever your JavaScript files are.


Step 4 Edit Your Page Template

Now let’s open up the page template you want the carousel to be shown in. Once you open it, wherever you want the carousel to be displayed, paste this code below:

<div class="list_carousel">
	<ul id="foo2">
		<?php
		$carouselPosts = new WP_Query();
		$carouselPosts->query('showposts=12');
		?>
		<?php while ($carouselPosts->have_posts()) : $carouselPosts->the_post(); ?>

		<li>
			<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($id, 'sliderimg'); ?></a>
			<div class="slidertitle"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>
		</li>

		<?php endwhile; ?>
	</ul>

	<div class="clearfix"></div>

	<a class="prev" id="prev2" href="#"><span>prev</span></a>
	<a class="next" id="next2" href="#"><span>next</span></a>
</div>

Now let me explain before you go nuts. The first part of the block of code is the name of the class (for styling of course) I’m calling it list_carousel. Next you’ll see that #foo2 id I told you about earlier. Next is the query for posts:

<?php query_posts('showposts=12'); ?>

I’m telling it to pull the latest 12 posts. That way, since I told it earlier to show 3 at a time, it can show 4 sets of 3 posts. But let’s say you want to be a little more specific and only show posts from a certain category. Then you’d use this code instead of the showposts code above:

<?php query_posts('category_name=slider&showposts=12'); ?>

What about tags you say? Well here you go:

<?php query_posts('tag=featured&showposts=12&offset=0&order=ASC'); ?>

Change “featured” to whatever tag you want to use. I’m also calling 12 posts and listing them in ascending order.

Confused yet? I Hope not. Ok, next on the main block of code above I’m pulling “sliderimg” the featured image of the post and also making it link to the actual post so of course when people click on the image, they’ll get taken to the post itself.

<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php echo get_the_post_thumbnail($id, 'sliderimg'); ?></a>

In my client’s case, they not only wanted to display an image in the carousel, they also wanted to display the title of the post itself. So below the image we’re displaying the post title, making it link to the post as well, and assigning a class to it called “slidertitle” so we can style that also.

<div class="slidertitle"><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></div>

*phew* Alright, at the very bottom are the previous and next buttons with the id’s prev2 and next2 that we stated in the JavaScript code earlier.

<a class="prev" id="prev2" href="#"><span>prev</span></a>
<a class="next" id="next2" href="#"><span>next</span></a>

Now that’s all explained, let’s move on!


Step 5 Style It With CSS

Well we do have it working now, but it doesn’t look anything like what we want… so open up your style.css file and paste this code and I’ll explain things below:

.list_carousel {
	height: 175px;
	margin: 0 auto;
	overflow: hidden;
	width: 660px;
}
.list_carousel ul {
	margin: 0;
	padding: 0;
	list-style: none;
	display: block;
}
.list_carousel li {
	font-size: 14px;
	color: #333;
	width: 200px;
	padding: 0;
	margin: 2px;
	display: block;
	float: left;
}
.list_carousel.responsive {
	width: auto;
	margin-left: 0;
}
.list_carousel .clearfix {
	float: none;
	clear: both;
}
.list_carousel a.prev {
	background: url("next-arrow-left.png") no-repeat scroll 0 0 transparent;
	display: block;
	height: 150px;
	position: relative;
	top: -174px;
	width: 50px;
}
.list_carousel a.next {
	background: url("next-arrow-right.png") no-repeat scroll 0 0 transparent;
	display: block;
	height: 150px;
	position: relative;
	left: 635px !important;
	top: -324px;
	width: 50px;
}
.list_carousel a.prev {
}
.list_carousel a.next {
	right: -29px;
}
.list_carousel a.prev.disabled, a.next.disabled {
	cursor: default;
}
.list_carousel a.prev span, a.next span {
	display: none;
}
#foo2 {
	left: 20px;
	margin: 0 2px;
	position: relative;
}

Yeah it’s a big block of code. Haha! Sorry I had a lot that I wanted to do with it as you can see. Let me try to make this as painless as possible. If you want to tweak the width, change the 660px and 175px to your desired width and height for the carousel. Also with .list_carousel li you can change the post title colors and width of each item. The .list_carousel a.prev and .list_carousel a.next classes are where the previous and next arrow images are being displayed. This was just how I needed it to look of course. Styling is up to you.


Here’s a Screenshot of the Finished Product

As well as a link to a live version: http://www.kstudiofx.com/carousel-tutorial

[Update:] This tutorial originally used query_posts(), which is bad practice in this context (as noted by Chip Bennett in the comments). We’ve updated the code to more appropriately use WP_Query().

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Snap

    oh snap, the demo doesnt move in ffox, IE or chrome
    http://www.kstudiofx.com/carousel-tutorial/

    new name: carou-stall ???

  • http://www.rafalborowski.com Rafal Borowski

    Live version doesn’t seem to work (latest chrome version for Windows)

  • http://endcore.com/ André

    The Demo doesn’t work for me, don’t see the both arrows to switch. :(

    • François

      Same here ;)

    • http://kstudiofx.com Carina
      Author

      all fixed thanks for letting me know

  • http://www.justforthealofit.com/ TheAL

    Should “wp_enqueue_scripts” be “wp_enqueue_script”? Perhaps that is why the demo doesn’t work?

    In all, very succinct and helpful. I am actually quite surprised that the js code isn’t much more voluminous. Js usually is. I’m going to be playing around with this over the weekend. Much thanks.

    • http://kstudiofx.com Carina
      Author

      actually it is scripts with an “s” you can double check in the docs here:

      http://codex.wordpress.org/Function_Reference/wp_enqueue_script

      and actually I did an elementary mistake of loading two different footers into my page template which caused the carousel to stop working. :b

      thank you for your comment!

      • TheAL

        I see now. Having wp_enqueue_script() in one part of the code, then wp_enqueue_scripts elsewhere, threw me for a loop. But that’s how WP manages it. Thanks.

  • Paolo

    …same here. Not working…

  • http://www.albert-pak.com Al

    Just tried demo, and it doesn’t work – arrows don’t show up.

    In console, got an error:

    TypeError: $(“#foo2″).carouFredSel is not a function
    items: 3

    • http://kstudiofx.com Carina
      Author

      should be working now.

  • http://kstudiofx.com Carina
    Author

    So sorry, all working =)

  • http://www.chipbennett.net/ Chip Bennett

    Please do not use query_posts(). Using query_posts() is inherently _doing_it_wrong() to begin with, but using it for a secondary loop is especially wrong.

    Use WP_Query() instead.

    • http://www.justforthealofit.com/ TheAL

      How would you rate the methods described here: http://www.binarymoon.co.uk/2010/03/5-wordpress-queryposts-tips/ – it’s a bit old, about 2 years, but I just came across it. Your comment reminded me of it.

    • http://kstudiofx.com Carina
      Author

      Thank you for the advice Chip. I’ve reworked the code on my live version to WP_Query and am working on a rewrite for this tutorial to use that code instead. thanks again!

      • http://wp.envato.com/ Japh Thomson
        Staff

        Post updated! Thanks for your feedback, Chip, and thank you Carina for your quick work on an update :)

    • http://iva-is.me Iva

      As someone who always wants to learn more, I would like to know why; so I can avoid that practice when necessary (or always…?!).

  • http://kustomdesigner.com mike

    I understand how you do this but I just dont see why you would want to do this.

    • http://www.rafalborowski.com Rafal Borowski

      I think it’s one of those “because I can” :)

      • http://kstudiofx.com Carina
        Author

        haha…just sharing the knowledge is all.

    • http://kstudiofx.com Carina
      Author

      One of my clients needed one and I couldn’t find one that functioned exactly as I needed so I had to make it myself.

  • http://www.customicondesign.com Custom Icon Design

    carouFredSel you mean slideshow? I cant understand when I saw it. It’s a sample slideshow page.

    • http://kstudiofx.com Carina
      Author

      carouFredSel is the name of the javascript code that I used.

  • http://rakateja.wordpress.com Made Raka Teja

    javascript doesnt work :) please help :)

    • http://kstudiofx.com Carina
      Author

      What’s the problem? Or Email me if you need some help.

  • Pingback: Tweet Parade (no. 37 Sep 2012) | gonzoblog.nl

  • http://www.geckowebsolutions.co.uk DanSiop

    Awesome Tut, got it working and its looking good.

    One question though. How can I get it to scroll across just 1 at a time.

    I want to display 3 posts as on the demo version but i dont want all 3 to move across when i click next or previous, just want it to slide across 1 at a time.

    Any ideas?

    • http://kstudiofx.com Carina
      Author

      should be as simple as changing 3 to 1 in the script code in step 3. if that doesn’t work, let me know.

      • Dan Siop

        Hello

        No that doesn’t work. That only changes the number of displayed items to 1. I want to display 3 and scroll across 1 at a time.

        How can I change this?

        Thanks

        Dan

        • http://kstudiofx.com Carina
          Author

          in step 3, change the code to this:

          jQuery(function($) {
          $(‘#foo2′).carouFredSel({
          prev: ‘#prev2′,
          next: ‘#next2′,
          auto: false,
          items: 3,
          scroll : {
          items : 1
          }
          });

          });

          This adds the scroll item number. change 1 to whatever you would like.

          • http://www.geckowebsolutions.co.uk Dan Siop

            Thank you so much, it works.

            Great tutorial and great support.

            Love it.

  • Boris

    Thank you very much Carina. I had a terrible day trying to find a carousel plugin for my wordpress site. No luck. And then your great tutorial. Aleluya!!! Thank you very very much. Sorry about my question I’m a newbie to JS. What if I need two or more carousels on one page, what do I have to change? Seems like I can’t call a function second time?

    • http://kstudiofx.com Carina
      Author

      Thank you Boris you just made my day =) I felt the same way… searched and searched everywhere for a plugin and i couldn’t find anything, i was amazed at the fact. Anyways… you would have to call it each time… like

      jQuery(function($) {
      $(‘#foo1′).carouFredSel({
      prev: ‘#prev2′,
      next: ‘#next2′,
      auto: false,
      items: 3,
      });
      $(‘#foo2′).carouFredSel({
      items: 1,
      });
      });

  • http://www.growcial.com DavidL

    Not working (Chrome Mac OS X)…I’ve followed your tutorial, but the arrows are not showing up. Code used below.

    TEMPLATE CODE
    —————————–

    query(‘showposts=12′);
    ?>
    have_posts()) : $carouselPosts->the_post(); ?>

    <a href="” title=”">
    <a href="” rel=”bookmark” title=”Permanent Link to “>

    prev
    next

    functions.php CODE
    —————————–
    if ( function_exists( ‘add_image_size’ ) ) {
    add_image_size( ‘sliderimg’, 200, 150, true );
    }

    function wptuts_load_caroufredsel() {
    // Enqueue carouFredSel, note that we specify ‘jquery’ as a dependency, and we set ‘true’ for loading in the footer:
    wp_register_script( ‘caroufredsel’, get_template_directory_uri() . ‘http://www.growcial.com/wp-content/themes/growcial/js/jquery.carouFredSel-5.5.0-packed.js’, array( ‘jquery’ ), ’5.5.0′, true );
    // For either a plugin or a theme, you can then enqueue the script:
    wp_enqueue_script( ‘wptuts-caroufredsel’, get_template_directory_uri() . ‘http://www.growcial.com/wp-content/themes/growcial/js/wptuts-caroufredsel.js’, array( ‘caroufredsel’ ), ”, true );
    }
    add_action( ‘wp_enqueue_scripts’, ‘wptuts_load_caroufredsel’ );

    wptuts-caroufredsel.js CODE
    —————————–
    jQuery(function($) {
    $(‘#foo2′).carouFredSel({
    prev: ‘#prev2′,
    next: ‘#next2′,
    auto: false,
    items: 3,
    scroll : {
    items : 1
    }
    });
    });

    • Boris

      Put next-arrow-left.png and next-arrow-right.png in your template directory. They will be your left and right arrow background images. The dimentions are 150×20 px if you didn’t change slideimage size.

      Read the css code carefully:

      .list_carousel a.prev {
      background: url(“next-arrow-left.png”) no-repeat scroll 0 0 transparent;
      display: block;
      height: 150px;
      position: relative;
      top: -174px;
      width: 50px;
      }
      .list_carousel a.next {
      background: url(“next-arrow-right.png”) no-repeat scroll 0 0 transparent;
      display: block;
      height: 150px;
      position: relative;
      left: 635px !important;
      top: -324px;
      width: 50px;

      • http://kstudiofx.com Carina
        Author

        thanks for the explanation

  • Jay

    How would you suggest adding custom post types to the loop? Thanks for the tut.

  • Jay

    Just in case anyone is interested

    $carouselPosts = new WP_Query(array(
    ‘post_type’ => array(
    ‘post’,
    ‘custom1′,
    ‘custom2′
    ),
    ‘showposts’ => ’12′)
    );

    • http://kstudiofx.com Carina
      Author

      thank you so much Jay!

      • http://twitter.com/saifulislam_3d SEO Expert

        right

  • Cơn gió lạ

    Great tut! :). But how to make it auto scrolling?

    • http://kstudiofx.com Carina
      Author

      in step 3, just change auto: false to auto: true.

  • Pingback: Very good circular and responsive jQuery carousel

  • Pingback: Настраиваем отображение записей в «карусели» | Wordpresso

  • Pingback: Best of Tuts+ in September 2012 | GMancer

  • Pingback: PSD+ Best of Tuts+ in September 2012 via buypappa.com | Buypappa blog

  • Pingback: Best of Tuts+ in September 2012 | SearchPsd Blog

  • Pingback: Best of Tuts+ in September 2012 | My Creative Directory

  • Pingback: Best of Tuts+ in September 2012 | DigitalMofo

  • Pingback: Best of Tuts+ in September 2012 | Wptuts+

  • Pingback: Best of Tuts+ in September 2012 | Wordpress Webdesigner

  • Pingback: My Stream | Best of Tuts+ in September 2012 | My Stream

  • Pingback: Best of Tuts+ in September 2012 | Omega Pixels

  • Pingback: Best of Tuts+ in September 2012 | Gamedevtuts+

  • Pingback: VEC+ Best of Tuts+ in September 2012 via buypappa.com | Buypappa blog

  • Pingback: NET+ Best of Tuts+ in September 2012 via buypappa.com | Buypappa blog

  • Pingback: Best of Tuts+ in September 2012 | t1u

  • Pingback: Best of Tuts+ in September 2012 | CSS Tips

  • Pingback: Best of Tuts+ in September 2012 | Abromed Nowoczesna Rehabilicacja

  • Pingback: Best of Tuts+ in September 2012 | Pixeldome

  • http://tru3design.com Travis

    I was having trouble using a custom post type and having a limited number of posts. This is what I ended up with that now works just in case anyone might need it.

    $carouselPosts = new WP_Query(‘post_type=sermon&posts_per_page=8′);

  • Pingback: Displaying Posts in a Carousel | ThemeMountain

  • http://www.facebook.com/perez.euclides Euclides Perez

    I didnt had the pleasure to meet caroufredsel , thank you for sharing and posting the tutorial, I will test it out as soon as possible!

  • http://www.facebook.com/viktor.harmens Viktor Harmens

    Hi Thanks, for the great tutorial. I am wondering how i can change the speed of the slider when i use auto: true.

  • http://twitter.com/saifulislam_3d SEO Expert

    nice

  • http://www.facebook.com/kaila.piyush Piyush G Kaila

    very nice

  • igmuska

    I am new to this. I’ve been intensely reading about multiple loops and noticed that your query might need “wp_reset_postdata()” just below your “endwhile” in order to include the carousel in a standard/custom theme page. But like I started, I am new, and have been studying the issues with calling multiple queries on page…

  • suryas

    i am trying to implement this on my site but the posts are displaying but the caroseul is not working

  • http://twitter.com/TheHungryMuse Jennie Tai

    I’m trying to install this on the footer of http://www.thehungrymuse.com but there’s something wrong with the code.. I’m not sure what I’m doing wrong. help!

  • dhanasekar

    Thanks you for the awesome tutorial

  • http://www.facebook.com/pexcornel Pex Cornel

    Hello. Can a carousel be used multiple times in the same page? I try and the first instance works but the second does not. What can I do?

    Thank you.

  • Carina
    Author

    Sorry everyone, I don’t get alerts if anyone comments, if you do need my help, feel free to email me w/ any problems you may have: kstudio@kstudiofx.com

  • Nick

    anyone have an idea as to how to make this code load random posts? Thanks!

  • Pingback: This Week In WordPress: Jan 7, 2013 - 2013 Web Design Trends

  • LekovicMilos

    I was doing everything like in this tutorial, and fixed issues that others mentioned, and my carousel is still not working! I had to change css too, at least to make it look like one carousel. It-s not moving, it just adds one # to my url. You can see it in action here: http://www.kojifilmdagledam.info .

    Code I am using is this:

    if ( function_exists( ‘add_image_size’ ) ) { add_image_size( ‘sliderimg’, 200, 150, true );}

    function wptuts_load_caroufredsel() {

    wp_register_script( ‘caroufredsel’, get_template_directory_uri() . ‘/js/jquery.carouFredSel-6.1.0-packed.js’, array( ‘jquery’ ), ’6.1.0′, true );

    wp_enqueue_script( ‘wptuts-caroufredsel’, get_template_directory_uri() . ‘/js/wptuts-caroufredsel.js’, array( ‘caroufredsel’ ), ”, true );

    }

    add_action( ‘wp_enqueue_script’, ‘wp_register_script’, ‘carouFredSel’, ‘wptuts_load_caroufredsel’ );

    That’s the code in functions file. In wptuts-caroufredsel.js file, the code looks like this:

    jQuery(function($) {

    $(‘#foo2′).carouFredSel({

    prev: ‘#prev2′,

    next: ‘#next2′,

    auto: false,

    items: 3,

    scroll : {

    items : 1

    }

    });

    });

    The file name of the third file is jquery.carouFredSel-6.1.0-packed.js, not 5.5.0.

    And the code that I put in html is this:

    query(‘tag=bioskop&showposts=12&offset=0&order=ASC’);

    ?>

    have_posts()) : $carouselPosts->the_post(); ?>

    <a href="” title=”">

    <a href="” rel=”bookmark” title=”Permanent Link to “>

    prev

    next

    You can go to the url I mentioned in the beginning of the comment, and see. What sgould I do?

    • http://www.facebook.com/carina.javier Carina Gomez
      Author

      those codes shouldn’t be in the .js file itself. those codes need to go in the page template you are using to display the carousel. also use the new wp_query code. here’s what i have in mine:

      query('category_name=wordpress&showposts=12');
      ?>

      have_posts()) : $carouselPosts->the_post(); ?>

      <a href="" title="">
      <a href="" rel="bookmark" title="Permanent Link to ">

      prev
      next

      • http://www.facebook.com/carina.javier Carina Gomez
        Author

        seems wp.tuts changed out my original article which is why everyone is having problems. here is a zip of my files that i currently use to make the carousel work on my live demo

        http://www.kstudiofx.com/CAROUSEL.zip

  • http://twitter.com/mark_rafferty Mark Rafferty

    The BIG PROBLEM is this is outdate and isn’t relevant to the latest jquery which makes it impossible to work with for anyone using any more up to date jQuery plugins. Of all the time vested in this site, please do keep it up to date?

    • http://wp.tutsplus.com/ Japh

      Hi Mark, can you please explain the exact problem you’re having? Then perhaps @666e826a5c98e1ffb29998371982a9da:disqus can update the tutorial with a fix.

  • http://www.facebook.com/carina.javier Carina Gomez
    Author

    ok i see what’s the problem with everyone not getting things to work. Seems wp.tuts has rewritten my article with different code. I’m not sure why, but that’s why people are having problems. here is a zip of my files that i currently use to make
    the carousel work on my live demo. if you need any help, let me know kstudio@kstudiofx.com

    http://www.kstudiofx.com/CAROUSEL.zip

  • http://www.facebook.com/umair.hamid.79 Umair Hamid

    I have multiple dynamic carousals on my page can you please tell me how to call this?

  • Mark

    Thanks great stuff, anyways i didn’t see the featured image in the post… after adding:

    if ( function_exists( 'add_image_size' ) ) {
    add_image_size( 'sliderimg', 200, 150, true );
    }

    So i added this function:

    add_theme_support( 'post-thumbnails' );
    In functions.php

    just before your code so the final result would be:

    add_theme_support( 'post-thumbnails' );

    if ( function_exists( 'add_image_size' ) ) {
    add_image_size( 'sliderimg', 200, 150, true );
    }

    function wptuts_load_caroufredsel() {
    // Enqueue carouFredSel, note that we specify 'jquery' as a dependency, and we set 'true' for loading in the footer:
    wp_register_script( 'caroufredsel', get_template_directory_uri() . '/js/jquery.carouFredSel-5.5.0-packed.js', array( 'jquery' ), '5.5.0', true );

    // For either a plugin or a theme, you can then enqueue the script:
    wp_enqueue_script( 'wptuts-caroufredsel', get_template_directory_uri() . '/js/wptuts-caroufredsel.js', array( 'caroufredsel' ), '', true );
    }
    add_action( 'wp_enqueue_scripts', 'wptuts_load_caroufredsel' );

    Maybe im really blind and im just missing something lol but anyways that worked for me :)