Building a jQuery Featured Posts Slider for WordPress

One of the most common requests in modern WordPress themes is the addition of a featured posts or featured image rotator. This is often a feature that users think makes a theme “premium”. Once you break down the code required,  it is actually much easier than it seems.

View Demo | Download Files

Also when combined with the WordPress 2.9 featured image feature (renamed in 3.0, it was previously called post thumbnail), it becomes much more powerful.

This technique can be seen in our themes Precision and Refresh.

A demo of what we are building.

Start by opening a containing div. Everything from here on will go inside this div. Note the ID because we will call it later.

[html]

<div id="photo-rotator">

[Featured Posts Here]

</div>

[/html]

Adding Featured Image Support

In order to let WordPress know that your theme supports featured images you need to add these line to the functions.php file:

[php]

add_theme_support( ‘post-thumbnails’, array( ‘post’ ) ); // Add support for posts
add_image_size( ‘nav-image’, 130, 40, true ); // nav thumbnail size, hard crop mode
add_image_size( ‘rotator-post-image’, 615, 280, true ); // large size, hard crop mode

[/php]

The values are for width (615) and height (280) in pixels. I like to specify multiple image sizes just in case I need more later. To do this just re-use the second line and change the name.

A New Query

With WordPress we use the loop to call in posts. Now you should not use the same loop twice on the same page. To work around this we are going to use WP Query.

[php]

<?php
$featuredPosts = new WP_Query();
$featuredPosts->query("showposts=4&cat=3");
while ($featuredPosts->have_posts()) : $featuredPosts->the_post();
?>

[/php]

Here we are showing up to 5 posts from the category with an ID of 3. You may use any of the standard query arguments to customize which posts show up. Just remove &cat=3 if you want to query all your posts. Using at least 1 argument is required (or at least it has caused me problems in the past!).

Now we get into the actual markup for each slide. Since this will be repeated for each post in the loop you only need to write it once.

[php]

<div id="slide-<?php echo $slide_id; $slide_id++;?>">
<a href="<?php the_permalink() ?>">
<?php the_post_thumbnail( ‘rotator-post-image’ ); ?>
<span><?php the_title(); ?></span>
</a>
</div>

[/php]

Then close the loop. The $slide_id is required so that we can tie the navigation to each specific post for linking. It increases by 1 for each post.

[php]

<?php endwhile; ?><!–/close loop–>

[/php]

Now for the Navigation

You probably want users to be able to move between the posts on their own, so we need to loop through our query again to create the post navigation.

[php]
<ul id="slide-nav">
<?php $nav_id=1; while ($featuredPosts->have_posts()) : $featuredPosts->the_post(); ?>
<li>
<a href="#slide-<?php echo $nav_id; ?>">
<span>
<?php the_post_thumbnail( ‘nav-image’ ); ?>
</span>
<? the_title(); $nav_id++;?>
</a>
</li>
<?php endwhile; ?><!–/close loop–>
</ul>

[/php]

And with that our PHP work is done.

Adding jQuery

We are using the jQuery tabs section to accomplish this, so you will need to include both jQuery and jQuery UI. WordPress has all the files you need built in, so you can use wp_enqueue_script(); to pull them in. Make sure to call in all the parts of jQuery Ui that you need.

[php]

<?php wp_enqueue_script(‘jquery’); ?>
<?php wp_enqueue_script(‘jquery-ui-core’); ?>
<?php wp_enqueue_script(‘jquery-ui-tabs’); ?>

[/php]

Now with to call in the jQuery UI Tabs function. With plenty of settings you can control speed, transitions, and much more. Read about it on the jQuery UI site.

[js]
jQuery(document).ready(function($){
$("#photo-rotator").tabs({fx:{opacity: "toggle"}}).tabs("rotate", 4000);
});

[/js]

Now for some Style

We’ve got functionality, now to make it pretty. Here are the styles I used to get started. You will need to modify this to match your site.

[css]
#photo-rotator {
background: url(‘img/background.png’) no-repeat 0px -10px;
width: 635px;
padding: 0px 10px;
height: 400px;
position: relative;
color: #fff;
margin: 20px auto 20px;
}

#photo-rotator .ui-tabs-panel {
list-style: none;
height: 300px;
}

#photo-rotator .ui-tabs-panel a.post-image {
display: block;
width: 615px;
height: 280px;
float: left;
margin: 10px;
background: #ccc;
position: relative;
text-decoration: none;
}

#photo-rotator .ui-tabs-panel a.post-image .title {
display: block;
padding: 10px;
background: #000;
background: rgba(0,0,0,.5);
color: #ccc;
position: absolute;
bottom: 0px;
left: 0px;
font-size: 18px;
width: 595px;
}

.ui-tabs-hide {display: none !important;}

#slide-nav {
padding: 0px;
margin: 0px;
position: relative;
float: left;
}

#slide-nav li {
float: left;
list-style: none;
}

#slide-nav a {
display: block;
color: #666;
float: left;
width: 138px;
padding: 12px 10px 10px;
text-decoration: none;
background: url(‘img/post-line.png’) no-repeat right top;
min-height: 100px;
font-size: 14px;
}

#slide-nav li:last-child a {
background: none;
}

#slide-nav a:hover {
color: #000;
}

#slide-nav a .thumbnail {
display: block;
background: #cbc9c9;
padding: 3px;
border-bottom: solid #fff 1px;
width: 130px;
height: 40px;
filter: alpha(opacity=50); /* Decreases opacity in IE */
-moz-opacity: .5; /* Decreases opacity in Firefox */
opacity: .5; /* Decreases opacity in Safari, Chrome, and Opera */
}

#slide-nav .ui-tabs-selected a { color: #222 }
#slide-nav .ui-tabs-selected a .thumbnail {
background: #bbb;
filter: alpha(opacity=100);
-moz-opacity: 1;
opacity: 1;
}

[/css]

I am linking to several images to add more style to the slider. You can get these images in the download file.

Wrapping it up

Our style here is pretty basic, but you can add more content and make your posts much more detailed. Plenty of great sites implement this feature. Please post in the comments if you have any questions or find some great examples of something similar being implemented around the web.

On WordPress Theme Options

Over the past year it has become trendy to build theme options pages crammed full of every possible setting. While it is well intentioned, I don’t think it is the best direction to take themes. In software design we always say that adding a preference should be your last resort. First you should try to design an elegant way, and add a setting only if absolutely needed. Thus avoiding unneeded complexity and setup time.

Adding more options actually makes the theme files more complex for someone trying to understand and customize the code that powers the website.

Start by removing options that aren’t really necessary. Here is Justin Tadlock on the subject:

One goal when making themes should be to avoid options by finding more intuitive ways for features to work. Ever heard of widgets?

So what does belong in a theme options page?

  • Theme style (Basically choosing a CSS file to reference)
  • Logo Upload (?)
  • Layout Switching (If it is crucial to the theme)
  • Custom text areas (though first consider if a widget would work)

Of course all of these depend on the theme.

Advertising

So you want to place small bits of code in assorted places throughout the site? Specifically places the user can control? This is perfect for a widget. No need for an entire tab of your options page devoted to configuring ads. Widgets are the answer.

SEO Options

Generally users need to customize page and posts titles,  meta information, and modify link attributes. While this can be important to a great site, it isn’t the role of a theme. WordPress has many great plugins that handle all the needed settings and more. Recently in their announcement of SEO settings in their themes WooThemes noted that it is compatible with the All-in-One SEO plugin. Meaning it is nothing more than duplicate functionality, and extra options for an end user to try and understand.

Navigation Menus

Since custom navigation menus are included in WordPress 3.0, you don’t need to make them part of your theme. If the theme already have this functionality I would recommend removing it with the next update.

Detailed Color Options

You’re a theme designer, right? Then the color decisions you made when designing the theme should be solid. It is good to design several different color variations the user can choose from, and even better to write your CSS so that it is easy to edit and understand. So having users be able to change the color of every link or heading from an options panel is excessive.

Now I don’t think this applies if you are trying to create a blank slate theme (i.e. Canvas, Headway, Thesis, etc).

Featured Images

With support for featured images in 2.9 (then called “Post Thumbnail”), you no longer need image resizing in your theme. Some say the built in WordPress support isn’t good enough, but I haven’t yet found a case where you couldn’t make it work.

Contact Forms

Forms are part of the functionality of the site, so they should be handled by plugins. There are some fantastic paid plugins (Gravity Forms) and some good free ones as well. Most commonly themes provide small contact forms to go in sidebars or footers. For that use a widget. Then it can be placed anywhere.

The Grey Areas

Here are the things I am not sure of their place in a theme or not. What do you think?

  • Analytics Code
  • Support Documentation (Just link to your knowledge base or support page. It isn’t needed as part of the theme)
  • Custom CSS
  • Number of posts on homepage (WordPress already has a posts per page setting)

On Style

Make it your options page design match WordPress. We don’t need a conflicting design style and user experience corrupting WordPress. Genesis is a great example of an options page that truly matches.

Simplicity

When it comes time to code the options for your next theme, keep it simple.


Note: sales from any affiliate links in the article go to WP Tavern. They deserve it.

Top 5 Reasons we use WordPress as a Content Management System

These days every site must have a content management system (CMS), or else it will very soon be outdated. Try selling a site to a client and then telling them they can’t actually update any of the content or photos themselves, somehow I don’t think they will be very happy.

Now in searching for a CMS to use you will come across everything from free, outdated systems such as Joomla, to some very expensive (think $50,000) corporate solutions that offer less functionality. In addition to that entire range a lot of development companies have created their own proprietary CMS. Having taken over clients from many of these development companies I can say that they usually produce nightmarish code, and have no documentation.

In a look search for the perfect CMS we finally settled on WordPress, no it’s not perfect, but here are the reasons we love it:

  1. Easy Template System. WordPress will integrate very quickly into an HTML and CSS template using some simple PHP tags. Once you get the hang of how it works, then you can convert a template over to a basic WordPress theme in minutes.
  2. Clean Code. WordPress outputs clean, semantic code. There are no outdated, table-based layouts, or anything else that gets in the way of web standards. Also the text editor will only let the user style text in a semantic way (such as using H1s for headers) that follows the CSS for the site (meaning the designer can set the style, and the site owner has to stay consistent with it).
  3. Robust Backend. Since the WordPress backend has been recently redesigned, it offers greater functionality. Some of the best web designers in the world worked on it, and it includes hours of usability studies. Know that your clients are using the best interface around.
  4. Regular Updates (including security). WordPress is updated regularly, which means that as soon as a security flaw is discovered, an update is sent out for it. Also you can rest assured that your client won’t be left years down the road with a system that is out of date. It will move with the times, and everything will just keep getting better.
  5. Excellent documentation. Some people say you should buy from them because they can offer something nobody else can. I say don’t, because if they aren’t around to fix it, then nobody else can and you will be stuck. With an open source system like WordPress you have excellent documentation and resources available including a huge support community. So if your web designer falls of the face of the earth it won’t be that hard to find someone else who can work with your system.

There are many more reasons, but those are the five that are most important to me and my clients. Do you have any more to add, or better yet, reasons you don’t like WordPress as a CMS?

Suckerfish Drop Down Menus with WordPress

Today we are going to answer a common question regarding WordPress navigation. How to create simple drop down menus that work across browsers. If you are at all familiar with the web standards approach, then you have probably heard of Suckerfish Drop Downs.

http://htmldog.com/articles/suckerfish/dropdowns/

Integrating this is mostly CSS, but here is the WordPress code to get us started:

[sourcecode language=’php’]

[/sourcecode]

That code gets our menu started in the standard WordPress way. We just added in the sort by menu order code so that you can control your page order. Also the depth of 3 is set because that is as far out as we are taking our CSS, so it wouldn’t make sense to let our HTML break it.

Now to get the basic CSS in place:

[sourcecode language=’css’]

#nav, #nav ul { /* all lists */
padding: 0;
margin: 0;
list-style: none;
line-height: 1;
}

#nav a {
display: block;
width: 10em;
}

#nav li { /* all list items */
float: left;
width: 10em; /* width needed or else Opera goes nuts */
}

#nav li ul { /* second-level lists */
position: absolute;
background: orange;
width: 10em;
left: -999em; /* using left instead of display to hide menus because display: none isn’t read by screen readers */
}

#nav li ul ul { /* third-and-above-level lists */
margin: -1em 0 0 10em;
}

#nav li:hover ul ul, #nav li:hover ul ul ul, #nav li.sfhover ul ul, #nav li.sfhover ul ul ul {
left: -999em;
}

#nav li:hover ul, #nav li li:hover ul, #nav li li li:hover ul, #nav li.sfhover ul, #nav li li.sfhover ul, #nav li li li.sfhover ul { /* lists nested under hovered list items */
left: auto;
}

#content {
clear: left;
color: #ccc;
}
[/sourcecode]

Now we have it working in all browsers except IE6 (which doesn’t properly support :hover). To support IE6 We need to add a few lines of JavaScript:

[sourcecode language=’JavaScript’]

sfHover = function() {
var sfEls = document.getElementById("nav").getElementsByTagName("LI");
for (var i=0; i<sfEls.length; i++) {
sfEls[i].onmouseover=function() {
this.className+=" sfhover";
}
sfEls[i].onmouseout=function() {
this.className=this.className.replace(new RegExp(" sfhover\b"), "");
}
}

}
if (window.attachEvent) window.attachEvent("onload", sfHover);

[/sourcecode]

That’s it!

Sliding Posts with WordPress

1. The Concept

Goal: To make a tabbed slider that displays WordPress posts from a specific category in an easy to use format. Making it simple to edit/delete posts, from the WordPress back-end, and still have a great, unique front-end result.

To start we are using the Coda-Slider from Niall Doherty.

http://www.ndoherty.com/demos/coda-slider/1.1.1/#1

Start by downloading and unzipping the files.

2. Making it Work With WordPress

We need to use the WordPress loop to make each page of the slider a tab. To do this we will start out with a post query for our category.

Create a new category to house our project (I called mine Portfolio), make sure to note the category ID as we will need it later. Based on the WordPress Template Hierarchy we know that any theme file named category-3.php (where 3 is your category ID) will be used to display posts from that category. So all code featured here will be inside that PHP file.

Place this in your header to link to the javascript files and to start the slider
[sourcecode language=’html’]

jQuery(window).bind(“load”, function() {

jQuery(“div#slider1″).codaSlider()

// jQuery(“div#slider2″).codaSlider()

// etc, etc. Beware of cross-linking difficulties if using multiple sliders on one page.

});

[/sourcecode]

To start with we want to analyze the code, and see where our loop should start. Remember that the loop is repeating code for each post, so we want it inside the containing DIVs. This slider code has three containing DIVs:

[sourcecode language=’html’]


[/sourcecode]

To start our loop we want to retrieve all posts in category with ID of 3 (make sure to replace 3 with your actual ID).

[sourcecode language=’html’]

For the next step we want to make sure the post title appears on the tab. To do this we need to add in the title section of the div.panel. As shown below.

<div class="panel" title="”>

[/sourcecode]
Then we will want to add our title and content within the wrapper div. Easy with the simple WordPress tags <?php the_title(); ?> and <?php the_content(); ?>.

Then everything needs to be closed off with three closing DIVs at the end.
[sourcecode language=’html’]

        

Here is our ending HTML:

<div class="panel" title="”>