• Skip to primary navigation
  • Skip to content
  • Skip to primary sidebar

HANDS ON WORDPRESS

Making a Living with WordPress

  • Home
  • Blog
  • About
    • About Hands On WordPress
  • The Austin WordPress Community
  • Contact
  • Show Search
Hide Search
You are here: Home / WordPress / How to Create a Custom Slider

How to Create a Custom Slider

sandibatik · May 3, 2011 · Leave a Comment

…Or, how I learned to stop worrying and love jQuery

Austin WordPress Meetup Notes — 5/3/2011

Image of Pat Ramsey
Pat Ramsey

Pat Ramsey lead tonight’s excellent demonstration of how to create Content Sliders in WordPress. He addressed the issue some WordPress developers face when they want the plugin, or method used, to behave just a little differently than the existing content slider options. Pat shared how he has learned to write his own custom content sliders.

Ramsey is one of the few presenters I know, that can present and explain code, and keep everyone engaged the whole time. Pat demonstrated how to make a content slider without the use of a plugin. He did a very good job of stepping through the various parts of the demo and explaining the PHP, CSS and JS code in a very understandable manner.  Pat’s way of explaining and breaking things down as he goes along, helps me and the other #WPATX members who are new to coding, better understand just how WordPress works and how to use it more fully.

A big thank you to Pat Ramsey for generously sharing the instructions and the code below with the members of the Austin WordPress meetup.

The basics of creating a custom content slider

There are several plugins for WordPress that enable content sliders on your WordPress site. In the mix, there are some very useful and handy ones. Dynamic Content Gallery, WP-Cycle, and WP-Rotator are three excellent slideshow plugins that I have used and are in my go-to list of WordPress plugins. That said, there always seems to be something that I don’t need or that I wish I had in one of these plugins. That’s when I look to writing my own custom slideshow tool using some WordPress code, CSS, and javascript to do exactly what I want.

There are three steps in this process:

  1. Write the query to grab the content. This is a custom Loop. Nothing really fancy there.
  2. Write the CSS to style the content.
  3. Include and write the necessary javascript to make it behave the way we want.

Writing the query

I believe it’s best to write the query in its own php template file. I created a file in my theme’s directory called slider.php. All my code for the custom Loop and the output will go here. Edit slider.php and add this code:

<div id="featured"> <!--The main container for our featured content -->
<?php
$featured_query = new WP_Query('cat=3&showposts=5'); // We create the query. Grab the 5 most recent posts in the category ID '3'
while ($featured_query->have_posts()) : $featured_query->the_post(); // Start our Custom Loop
$do_not_duplicate[] = get_the_ID(); ?>

<div class="featuredcontent">
<?php the_post_thumbnail( 'Featured_Slider' ); ?>
<div>

<h3><a href="<?php the_permalink() ?>">?php the_title(); ?></a></h3>

<p><a href="<?php the_permalink() ?>"><?php get_the_excerpt(); ?></a></p>
</div>
</div>
<?php endwhile; ?>
</div>

In the beginning of the code, we create a new query:

$featured_query = new WP_Query('cat=3&showposts=5');

You can customize this to your needs – I advise reading up on query_posts and wp_query in WordPress’s Codex.

After we create our new query, we output the results. In our case, we show the Featured Image, the title and the excerpt, both linked to the Post’s permalink. Slider.php is included in my theme using the get_template_part(); template tag in my index.php file. Place get_template_part(); where you want the slider to appear:

<?php get_template_part('slider'); ?>

The CSS

Now we need to write some CSS rules to format the content for our slider:

#featured {
position: relative;
z-index: 1;
height: 420px;
margin-bottom: 1.3em;
background-color: #000;
}

#featured .featuredContent {
overflow: hidden;
float:left;
width: 640px;
height: 420px;
}

#featured .featuredContent .featured_text {
position: absolute;
top: 310px;
width: 620px;
height: 100px;
padding: 10px 0 0 20px;
background-color: rgba(0,0,0,0.8);
z-index: 2;
}

#featured .featuredContent h3 {
color: #fff;
margin: 0 0 0 0;
}

#featured .featuredContent h3 a,
#featured .featuredContent h3 a:visited {
color: #fff;
font-weight: 800;
font-family: Helvetica,San-serif;
text-decoration: none;
}

#featured .featuredContent p {
color: #fff;
margin: 0 0 0 0;
font-family: Helvetica,San-serif;
font-size: 0.9em;
line-height: 1em;
}

#featured .featuredContent p a,
#featured .featuredContent p a:visited {
color: #fff;
text-decoration: none;
}

Make slider go fast now

We’ve created our new query, we’ve styled its content, now we add in the behavior – the sliding, fading, etc. The first example is a bit of javascript, using jQuery, that makes the divs with the class of featuredContent fade in & out. The second example uses jQuery Cycle. Both examples require you to enqueue WordPress’s included jQuery and an external javascript file you’ll create in your theme’s directory.

First, how do you properly load jQuery and your external javascript? If you add script tags in your theme’s header, you run the risk of loading javascript twice & possibly conflicting with javascript loaded by a plugin. The proper way to load javascript is to use the wp_enqueue_script function.

In your theme’s functions.php, add this code:

add_action('init','my_scripts');
function my_scripts() {
wp_enqueue_script(
'my.js',
get_bloginfo('template_directory') .'/js/my.js',
array('jquery'),
'1.1',
false
);
}

You can repeat the wp_enqueue_script function for other scripts you need to load.

For both examples, I created a file in my theme’s directory called my.js. This is where we write any custom javascript.

A simple fader using just jQuery

This example calls jQuery, then runs a script which fades the .featuredContent divs.

jQuery(document).ready(function($) {

var jS = $('div.featuredContent');
jS.hide(); // not needed if css hides elements initially
var i = 0;
function do_ticker() {
jS.eq(i).fadeIn(500, function() {
var me = $(this);
setTimeout(function() { me.fadeOut(500,
function() {
i = ++i % jS.length;
do_ticker();
});
}, 5000); // setTimeout
});
};
do_ticker();

});

The first and last lines load jQuery, in-between goes our custom javascript.

var jS = $('div.featuredContent'); //the element that's fading in & out - div class="featuredContent"

jS.eq(i).fadeIn(500, function() {
var me = $(this);
setTimeout(function() { me.fadeOut(500,

//500 is the duration of the transition in milliseconds (half a second) - how long both the fadein & fadeout take


}, 5000); // setTimeout in milliseconds (5 seconds) - how long each slide is visible

Why use the custom jQuery code instead of an effects plugin like jQuery Cycle? 1) You just want a fader, nothing more. 2) You want to minimize the amount of code you’re loading. That said, if you need some flexibility in the transitions, something like jQuery Cycle might be best.

Using jQuery Cycle

jQuery Cycle is a slideshow plugin for jQuery that lets you use many different types of transitions – not just fading. To use it, we need to do two things differently:

1) load jQuery Cycle using wp_enqueue_script.

2) write some custom javascript.

Using our my.js file, we replace the custom javascript with this:

jQuery(document).ready(function($) {

$('#featured').cycle({
fx: 'fade', //replace fade with other transition types to use different effects
speed:500, //how fast the fade takes place
timeout:5000 //how long each slide stays on screen
});

});

You’ll want to load jQuery Cycle before you load your custom javascript.

add_action('init','my_scripts');
function my_scripts() {
wp_enqueue_script(
'cycle',
'http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js',
array('jquery'),
'1.1',
false
);
wp_enqueue_script(
'my.js',
get_bloginfo('template_directory') .'/js/my.js',
array('jquery'),
'1.1',
false
);
}

You’ll notice we’re loading jQuery Cycle from Github. If you want, you can place a copy in your theme’s directory and include it from there, as we do with my.js.

There we have it. A custom query, some CSS, and some javascript and you have a customized content slideshow in your WordPress theme. At the May Austin WordPress Meetup, I presented this using TwentyTen as the base theme. I’ve zipped that copy of TwentyTen with the custom code included. Enjoy!

Thanks to Pat for guiding us through building a content slider. The organizers of the Austin WordPress meetup look forward to seeing you at a meetup soon. Check out wpaustin.com for summaries of past meetups. Follow @wpatx and @pat_ramsey on Twitter.

 

Filed Under: WordPress Tagged With: Code.WordPress Tutorials, Content Management, Content Sliders, CSS, JS, PHP, WordPress Tips & Tricks

Reader Interactions

Leave a Reply Cancel reply

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

Primary Sidebar

About Sandi Batik

About Sandi Batik

Introverted Freelancer, WordPress trainer, consultant, curricula developer, author, unapologetic geek, unrepentant capitalist, lucky enough to do what I love … more about me about About Sandi Batik

  • Twitter

Search

Introverted Freelancer

Traits of Successful Introverted Freelancers

Traits of Successful Introverted Freelancers

2017 Business Check-up Workshop

2017 Business Check-up Workshop

Expanding Your Business With Automated Marketing Funnels

Expanding Your Business With Automated Marketing Funnels

How to Use Permission Marketing to Build Your WordPress Business

How to Use Permission Marketing to Build Your WordPress Business

How Much Should I Charge for Building or Designing a WordPress Website?

How Much Should I Charge for Building or Designing a WordPress Website?

Project Management

Keeping Scope Creep From Killing Your Schedule and Profit Margin

Keeping Scope Creep From Killing Your Schedule and Profit Margin

Project Management for WordPress Freelancers

Project Management for WordPress Freelancers

WordPress

Securing and Maintaining Your WordPress Site

Securing and Maintaining Your WordPress Site

How The WordPress Media Library Works — 2018

How The WordPress Media Library Works — 2018

How To Build an Information Structure for Your WordPress Site

How To Build an Information Structure for Your WordPress Site

How WordPress Themes Really Work

How WordPress Themes Really Work

How to Create and Manage eMail Newsletters from Your WordPress Site

How to Create and Manage eMail Newsletters from Your WordPress Site

How to Secure and Maintain Your WordPress Site

How to Secure and Maintain Your WordPress Site

Copyright © 2010-2023 Hands On WordPress · All Rights Reserved