Part 3: Making A Dynamic WordPress jQuery Featured Post Slider Tutorial
Let's just dive right in
So the first thing you need to do, since it's always a good idea to include your CSS styles before you call your JavaScript files to be sure that all the declarations have been loaded, you need to make a stylesheet. In the interest of time, and the fact I've been up all night writing a different even longer post, I'm just going to use the code I created for the slider on the homepage. It's basically the same code used for the static slider in part 2, minus the Php. If you do use this code, please just change the images to point to your own images.
Tutorials in this series
- Part 1: Creating Your Own Custom Loops In WordPress
- Part 2: The Static Version Of The jQuery Featured Post Slider
- Part 3: Making A Dynamic WordPress jQuery Featured Post Slider
Step 1: The Stylesheet
Nothing really new here except I added the #slider_wrap ID which wraps the entire homepage slider box up and keeps it together. A few other small things are different too.
/* Slider */
#slider_wrap {
position:relative;
width:914px;
height:305px;
margin:0 auto;
padding:0px;
background: url(images/SLIDER_BACKGROUND.png) top center no-repeat;
}
#slider {
width: 610px;
height:240px;
border: 0px solid #ddd;
float:right;
margin-top:40px;
}
#slider ul {
margin: 0;
padding: 0;
list-style-type: none;
height: 1%; /* IE fix */
}
#slider ul:after {
content: ".";
clear: both;
display: block;
height: 0;
visibility: hidden;
}
/* Slider > SLIDES */
#slider .slides {
overflow: hidden;
width: 425px;
float:left;
}
#slider .slides ul {
width: 2880px;
float:left;
}
#slider .slides li {
width: 425px;
float: left;
padding: 10px 0px;
background:transparent!important;
}
#slider .slides h2 a {
margin-top:-20px!important;
padding-top:0px;
font-size: 16px;
}
#slider .slides .postsnip {
float: right;
margin-right:0px;
margin-top:0px;
width:200px;
height:200px;
overflow:hidden;
padding:0px;
}
#slider .slides #readmore {
float:left;
margin-left:250px;
position:relative;
}
/* slider > NAVIGATION */
#slider .slides-nav {
border-top: 0px solid #ccc;
width: 184px;
float:right;
clear:left;
z-index:100;
padding:0px;
margin:20px 0px 0px 0px;
height:225px;
overflow:visible;
}
#slider .slides-nav li { margin-left:4px; }
#slider .slides-nav li a {
display: block;
padding: 13px 10px;
outline: none;
background: url(images/INACTIVE.png) center center no-repeat;
color:#fff;
text-decoration:none;
font-weight:bold;
font-size:14px;
font-family: arial;
}
Don't forget the part that adds the "active" class to the navigation tabs.
.js #slider .slides-nav li.on, .js #slider .slides-nav li.on a {
background: url(images/ACTIVE.png) left center no-repeat;
color:#000;
margin-left:0px;
}
.js #slider .slides-nav li.on a {
position: relative;
top: 0px;
}
I also threw this in since it's what I used in the slider on the homepage, but you can remove it or change it however you like. It may come in handy too, since it will basically add a box on the left of the slider, that you can widgetize or something else to it.
/* slider_wrap - Most Popular Posts */
#slider_wrap .popular-post {
float:left;
width: 250px;
position: relative;
overflow: hidden;
clear:both;
margin-top:25px;
margin-left:20px;
color:#cdcdcd;
}
#slider_wrap .popular-post h2 {
color: #182431!important;
margin-bottom:4px;
font-size:20px;
font-weight:bold;
font-family:Verdana, Arial, Helvetica;
text-shadow:1px 0px 1px #fff;
}
#slider_wrap .popular-post p { display: none; }
#slider_wrap .popular-post ul {
margin:10px 0px 0px 0px;
padding:0px;
}
#slider_wrap .popular-post li {
margin:0 0 2px 0;
padding:0px 0 7px 0px;
list-style:none;
color:#cdcdcd;
}
#slider_wrap .popular-post li a {
color: #fff;
text-decoration: none;
font-size:12px;
font-weight: bold;
font-family:Arial, Verdana, Helvetica;
}
#slider_wrap .popular-post li a:hover {
color: #cdcdcd;
text-decoration: none;
}
That's all there is for the CSS, now just add that to your theme CSS template styles.css and you're good to go.
Step 2: Including jQuery and JavaScript Files
Now you can add jQuery to your theme. I have included my .js files in the footer.php template of my WordPress theme so that it will load faster and after the page but you can add it to your <head> of your header.php if you choose, just put it below your CSS styesheet reference.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
In order for this slider to show only on the homepage, we have to use the is_home() function in WordPress to check if we're on the homepage or not. Therefore, if the slider isn't being shown, then the JavaScript files that are included which are needed for just the slider don't need to show unless on the homepage. So add this to your theme. I've also added this to my footer, below the jQuery include.
<?php if(is_home()) { // checks if on homepage - index.php ?>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/jquery.cycle.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/js/slider.js"></script>
<?php } ?>
You can download the jQuery Cycle plugin here as mentioned in part 2. Then create the file slider.js if you haven't already when doing the static slider from part 2, and add this code to it. Save both of these to your /js folder on your server.
Step 3: The jQuery Script
There's nothing different about this from the static slider in part 2. If you didn't do part 2 you can tell from the comments in the code what's going on here.
$slideshow = {
context: false,
tabs: false,
timeout: 3000, // time before next slide appears (in ms)
slideSpeed: 1000, // time it takes to slide in each slide (in ms)
tabSpeed: 300, // time it takes to slide in each slide (in ms) when clicking through tabs
fx: 'scrollLeft', // the slide effect to use
init: function() {
// set the context to help speed up selectors/improve performance
this.context = $('#slider');
// set tabs to current hard coded navigation items
this.tabs = $('ul.slides-nav li', this.context);
// remove hard coded navigation items from DOM
// because they aren't hooked up to jQuery cycle
this.tabs.remove();
// prepare slideshow and jQuery cycle tabs
this.prepareSlideshow();
},
prepareSlideshow: function() {
/* initialize the jquery cycle plugin -
* for information on the options set below go to:
* http://malsup.com/jquery/cycle/options.html */
$('div.slides > ul', $slideshow.context).cycle({
fx: $slideshow.fx,
timeout: $slideshow.timeout,
speed: $slideshow.slideSpeed,
fastOnEvent: $slideshow.tabSpeed,
pager: $('ul.slides-nav', $slideshow.context),
pagerAnchorBuilder: $slideshow.prepareTabs,
before: $slideshow.activateTab,
pauseOnPagerHover: true,
pause: true
});
},
prepareTabs: function(i, slide) {
/* return markup from hardcoded tabs for use as jQuery cycle tabs
* (attaches necessary jQuery cycle events to tabs) */
return $slideshow.tabs.eq(i);
},
activateTab: function(currentSlide, nextSlide) {
// get the active tab
var activeTab = $('a[href="#' + nextSlide.id + '"]', $slideshow.context);
// if there is an active tab
if(activeTab.length) {
// remove active styling from all other tabs
$slideshow.tabs.removeClass('on');
// add active styling to active button
activeTab.parent().addClass('on');
}
}
};
$(function() {
// add a 'js' class to the body
$('body').addClass('js');
// initialize the slideshow when the DOM is ready
$slideshow.init();
});
Now that the basic stuff is all taken care of we can dig into the more complex code.
Step 4: The Part You've Been Waiting For
I'm going to go through through this piece by piece and explain it. Then show the entire code at the end. What this does basically is creates 2 different WordPress loops, that query the database for posts from the category you set. The first loop displays the post titles for the tab navigation, and the second displays the slides consisting of a post thumbnail custom filed, the excerpt and post title. Let's look at it more.
Wrap the entire block of code with an the on homepage check if (is_home() { then open the slider_wrapper and throw in a widgetized area for the .popular-post
section if you want, then open the slider and slides-nav divs.
<?php if (is_home()) { // show the popular posts and slider if(is_home() ?>
<!-- Begin Home page Slider -->
<div id="slider_wrap">
<div class="popular-post">
<?php // ADD YOUR POPULAR POSTS SCRIPT HERE, OR OTHERWISE WIDGETIZE THIS SECTION ?>
</div>
<div id="slider">
<ul class="slides-nav">
Next, create a variable $featuredPosts and use the WordPress function WP_Query() I went over in part 1 using custom loops. Instantiate a query getting 5 posts from the category 7, with 7 being the cat_IDof your Featured category. In the admin you can hover over the category links to see what each category ID is.
Then create a for()loop which will be used to count the posts, and display a number in the href of each list item so it will be used to add +1 for each #slide-COUNTER. Use a while() loop just like I showed in part 1, for looping through the posts as you would any other time.
Finally, show the list item, with the class .on and the href= #slide-$i as I explained above. Then show the title so you can control how many characters will show so the the text won't wrap in the navigation. Use substr($post->post_title,0,17) where 17 is the number of characters to show. This will also be used for the title and the excerpt in the next part. End the while and for loops and close the list.
<?php
$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=5&cat=7');
for($i=1; $i<=$featuredPosts; $i++) { // start for() loop
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); // loop for posts titles
?>
<li class="on"><a href="#slide-<?php echo $i++; ?>"><?php echo substr($post->post_title,0,17); // short title ?>...</a></li>
<?php endwhile;
} // end for() loop
?>
</ul>
Now for the .slides div and unordered list. First set up the same $featuredPosts variable, WP_Query(), for() and while() loops as you did before. The display the list item with the ID slide- $i which is adding the post that is showing based on the href value of the navigation. This is what makes the slider function as a tabbed menu when JavaScript is disabled.
<div class="slides">
<ul>
<?php
$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=5&cat=YOUR_FEATURED_CATEGORY_ID');
for($i=1; $i<=$featuredPosts; $i++) { // second for() loop for post slides
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); // loop for posts
?>
<li id="slide-<?php echo $i++; ?>" class="clearfix">
Then open up the .thumb div add the link to the post. Assuming you want to display the image with a custom field set per post, the image source is echoing the result of the get_post_meta() which is is getting the post ID, the custom field 'key' = Thumbnail, or whatever you set your featured post thumbnail image as in the custom field, and returns true. Add an alt and title attribute, and maximum width and height of 200px.
<div class="thumb clearfix"> <a href="<?php the_permalink(); ?>"><img src="<?php echo get_post_meta($post->ID, "Thumbnail", true); ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" width="200" height="200" /></a>
Step 4.5: Take A Breather
That was tiring...
Now create the excerpt div with the post snippet (.postsnip) class, display the H2 title using the method from above to shorten the number of characters, this time to make sure it doesn't wrap to 3 lines or more than 30 characters. Then echo the excerpt the same way only using $post->post_excerpt,0,275 cutting it to 275 characters. Close out the divs, and if you want add a "Read more" image link here which will show outside the box. Finally close out the list item, the loops, and everything else. Make sure to add the closing } to close the if (is_home()) { function that was opened at the beginning of the code block.
<div class="postsnip">
<h2><a href="<?php the_permalink(); ?>"><?php echo substr($post->post_title,0,30); // short title ?>...</a></h2>
<?php echo substr($post->post_excerpt,0,275); // show shortened excerpt ?>...
</div>
</div>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/read-more.png" alt="<?php the_title(); ?>" title="Read more: <?php the_title(); ?>" id="readmore" /></a>
</li>
<?php endwhile;
} // end for() loop number 2
?>
</ul>
</div>
</div>
</div>
<!--/End homepage Slider-->
<?php } // end if(is_home() ?>
Step 5: The entire Code
Not really a step, but hey I just wrote all that out in about 20 minutes so I'm not thinking clearly. Here's the entire code I just went through and broke down for you.
<?php if (is_home()) { // show the popular posts and slider if(is_home() ?>
<!-- Begin Home page Slider -->
<div id="slider_wrap">
<div class="popular-post">
<?php // ADD YOUR POPULAR POSTS SCRIPT HERE, OR OTHERWISE WIDGETIZE THIS SECTION ?>
</div>
<div id="slider">
<ul class="slides-nav">
<?php
$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=5&cat=7');
for($i=1; $i<=$featuredPosts; $i++) { // start for() loop
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); // loop for posts titles
?>
<li class="on"><a href="#slide-<?php echo $i++; ?>"><?php echo substr($post->post_title,0,17); // short title ?>...</a></li>
<?php endwhile;
} // end for() loop
?>
</ul>
<div class="slides">
<ul>
<?php
$featuredPosts = new WP_Query();
$featuredPosts->query('showposts=5&cat=YOUR_FEATURED_CATEGORY_ID');
for($i=1; $i<=$featuredPosts; $i++) { // second for() loop for post slides
while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); // loop for posts
?>
<li id="slide-<?php echo $i++; ?>" class="clearfix">
<div class="thumb clearfix">
<a href="<?php the_permalink(); ?>"><img src="<?php echo get_post_meta($post->ID, "Thumbnail", true);?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>" width="200" height="200" /></a>
<div class="postsnip">
<h2><a href="<?php the_permalink(); ?>"><?php echo substr($post->post_title,0,30); // short title ?>...</a></h2>
<?php echo substr($post->post_excerpt,0,275); // show shortened excerpt ?>...
</div>
</div>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><img src="<?php bloginfo('template_directory'); ?>/images/read-more.png" alt="<?php the_title(); ?>" title="Read more: <?php the_title(); ?>" id="readmore" /></a>
</li>
<?php endwhile;
} // end for() loop number 2
?>
</ul>
</div>
</div>
</div>
<!--/End homepage Slider-->
<?php } // end if(is_home() ?>
Step 6: Subscribe and Comment
So now that you've just finished this and the other 2 tutorials in this 3 part series, are you going to subscribe to the feed or leave a comment? Or maybe you want to check out some more fun and useful WordPress tips tricks and tutorials. Hope this was useful for you, and got something out of it.
If you're looking for a demo of this, just visit the homepage of this site. The slider at the top of the page there is what I based this entire 3 part tutorial series on. I will work on creating a single demo page for just the slider, but only if you comment asking for one.
Here is another slider tutorial I wrote using a different jQuery plugin. In case you need a different perspective on things.








User Comments
( ADD YOURS )Tim February 22
Thanks Jared, I'm just building a couple of new wordpress sites and spotted this. I think it's a nice idea, seems to work well on your site. I'll give it a go and give you some feedback if I manage to get it to work with my rather limited jquery & WP knowledge.
Jared February 22
Cool, if you need any help with it let me know. I know it wasn't the very best way to create the loops, for example, making 2 for() loops and 2 while loops, which are exactly the same.
I just wrote this really quickly, and will be working on a more efficient and updated version.
Jared February 22
Oops, I forgot to fix the the comments.php. Don't worry about my gravatar showing next to the comment form to the next person who comments.
For some reason it shows the image of the last person to comment, and I need to fix it. If anyone knows how to do that, let me know! Save me some debugging time. :)
Revka Stearns February 23
Thank you, thank you, thank you! You gave me the clue I needed to figure out how to code my slider to only show posts from a specific category. It a completely different slider, but you were a huge help when I was ready to tear my hair out.
You can see it here http://sisterlysavings.net.
Again, thanks a million.
Jared February 23
Your welcome :)
That's the whole reason I made this post, because I know how very stressful it can get doing something, like when I was making this I was freaking out trying to get it to work.
I like what you did, jCarousel slider?
moritz February 27
Found this, like this but don't get it working. The first loop is not going to end and pops out thousands of #slider-$i. Can't find the mistake, i am not a php/jQuery pro, even though i found out that you forgot one ?> in line 44.
http://www.onemonkey.de/www/moritzschefers
adsl viettel April 24
It's hard for newbie like me to follow the instruction of your post :(
Jared April 26
What are you having trouble with?
darnoji April 30
This is what I've been looking for..Very nice tutorial.
Thanks alot
Pacster May 26
Ey there, I would really like to thank you for putting together this series, I found them truly useful when creating a custom featured slider a few days ago. I really appreciate the fact that you took the time and went through the code in detail!
I would like to share a little tweak: instead of using the post titles for creating the tabbed menu, you can use
<a href="#slide-">
This way you get '1, 2, 3' etc., in case you need to save space or a more discreet pager.
Thanks again, I'm looking forward to be as sharp and share this kind of tuts!
Jared May 26
Hey Pacster, thanks for the kind words. I'm glad it helped you out :)
I know that I could've used numbers instead of the post titles for the tabbed nav. Though that was just too easy :P and not what I had done for the slider on this site, which was what I was showing how to create.
bannersky June 2
Thanks for sharing.
Jeremy June 3
This is great, but you never actually said what script / code goes into which pages and what sections.
Jared June 10
I have a separate js file which I put the javascript code from step 3 in which is included either in the footer or header the way you would any js file, after jQuery is included.
The Php code is put where ever you would like the slider to show up, in my case I put it in my header file.
Andy Bailey June 15
I found this tutorial after literally days of searching for a plugin to do a featured post sliding panel. DAYS!!
I was here for 1 hour and now I have a slightly modified version running on my new theme which is due to be live soon. Thanks a million, this surpassed any of the plugins I tried!
I subscribed by email straight away!
Jared June 15
I know exactly how it is trying to find something like this. I spent months searching for a way to do this before I finally managed to come up with this. Which is why I made this tutorial. I've been there, and know it's very difficult to find just what you're looking for.
I'm happy to help :)
piyashrija June 26
thanks u made miee day.. grt tutorial
Freelance webdevelopment July 6
This is a great tutorial Jared! I've been using WP for a short while now (I was a MODx addict in the past) and I was looking for a decent slider liked this. I've tried it out now and it all seems to work fine!
Thanks for the hard work! Have you got more of these tutorials coming up?
Jared July 6
Thanks and glad to hear it's working for you :)
I always have more tutorials and other crazy and cool ideas on in the works. As far as making another jQuery slider tutorial such as this, I really can't say for sure. It is possible. After all, it is the second slider tut I've written for pulling WP content into it.
I am always open to any suggestions or special requests for anything you would like me to write about. Just let me know, and I'll see what I can do :)
bazel July 10
great tutorail. how to change the fx used? I tried changing fx: 'scrollLeft', to"zoom"
but nothin happen
thanks
Jared July 12
I haven't tested anything other than 'fade' as an fx. Though it should work, the fx you should be able to use are for the cycle plugin: http://malsup.com/jquery/cycle/
john wallace July 27
Great tutorial! Question: It works fine for me with google hosted jquery but doesn't work with the jquery included with wordpress. Any clues?
Jane July 29
hi jared. i'm noob when it comes to wordpress, would it be possible to include on your post if we need to create another file for the codes you mentioned, and/or on which file to put them? i appreciate if you can. thank you.
Kev August 2
Nice tutorial, but How do are you calling the three scripts: jquery, jquery.cycle , slide-style.js in wordpress?
Are you using wp-enqueue-script? Because I'm unable to get it to work using wordpress templates.
Jared August 6
DId you read Step 2: Including jQuery and JavaScript Files
That's the part that explains what I've done to call the scripts.
kev August 8
Jared:
Your example file works but when I try to call it with my application it's conflicting probably due to bps' incompatibility.
Jared August 8
I don't know what bps is exactly, so I wouldn't be able to tell you whether that was the issue or not.
PhanKimi August 13
Thanks for this awesome tut ^^
Jeremy August 17
It's been a few months since I could get back to trying this out. I moving along kind of nicely, but I'm having the problem where I have a never ending loop like Moritz had back in February. Have you run into that problem at all?
Jeremy August 19
To follow up on this, if I edit this spot:
for($i=1; $i got accidentally commented out. I'll try and type the whole script line by line without the comments tonight and see if that fixes it.
Sorry if I'm putting too much info on here, I just think this is a great tutorial if I can get it to work and others might be interested in the results. Thanks for your efforts and any help you can provide!
Name... August 19
// for($i=1; $i<=$featuredPosts; $i++)
Jared August 19
I'm not sure I understand what your problem is Jeremy.
If you are trying to fix an infinite loop, make sure you close any for() loops you may not have closed. That's the only cause I can think of for having an infinite loop.
Adda August 22
This tutorial is absolutely amazing. I just implemented it on a site I am developing which I will link you to as soon as its live.
My only question is that I seem to have one weird quirk going in mine. When the page loads, ALL of the slider-nav li are highlighted as if they are all "on." As soon as the first slide moves out of the way the slider-nav act as they are supposed to and are highlighted only when showing the corresponding slide.
Any ideas as to what the problem is?
Thank you!!!
Jared August 23
That happens to the slider on the homepage here too. I gave it a little look into when I first made it, but I didn't really care to stress out on it so never figured it out. If you find a way to stop it let me know. I won't be trying to fix it though, I just don't have the time or motivation to at this point.
Glad you like the tut too :)
Adda August 23
Gotcha, no worries, I will try and figure it out and let you know when I do.
Thanks again!
Mark August 31
Just what i was looking for! But as I was trying this one out with the static version, the slider nav just disappears. No new tabs were generated from the slider js. Can anyone help me? Thanks.
You can find the problem here:
http://www.espizone.com/clients/thefamily/
Trackbacks