Using Nivo Slider In WordPress With Custom Captions

/ HTML, Javascript, Misc / by Paul Robinson / 138 Comments
This post was published back on February 20, 2011 and may be outdated. Please use caution when following older tutorials or using older code. After reading be sure to check for newer procedures or updates to code.

As I said Andy asked if it was possible to use Nivo’s custom captions inside WordPress, and while I did answer in the comments, I think it’s worthy of it’s own post to explain what is going on inside the code.

If you missed the first post on Nivo slider you’ll need to go back and follow that before you can continue on with this tutorial.

I’m going to explain how to do it in two ways. The first is using the post title, and the second will be with a custom field. All modifications are made to the theme file with the Nivo slider HTML inside, not the functions.php file.

Custom Captions: Post Title

Okay, first let’s refresh our memory with what the code we have right now looks like:

This code generates the images that will be used for the slider, as well as the HTML & captions.

Because we all like pictures to spice up a post, and because I want to show you the only difference between the sliders is the caption’s contents, here is what we are shooting for.

Image from Chuck. © NBC Studios. No infringement intended. Used for illustrative purposes only.

As you can see the slider is showing the title of the post in the caption. So let’s dive into the code that makes this magic happen. The code is nearly the same as before but has some new lines thrown in, because of that I’m going to highlight both the modified & new lines.

What we are doing in the code is creating an array to hold the title of each post. Then outputting it after the slider as Nivo requires the captions to be placed in div elements outside the slider element. We use a foreach to run through the titles we saved.

An important thing to notice is the use of $key in the caption code and the use of count() in the main code. Nivo requires the id of the div element with the caption to match the title of it’s corresponding image. This is how it matches the caption with the image. To help deal with that we count how many entries we have in the array holding the titles so far and minus one. We do this because the array key counts from zero & count() counts from one. This makes the ID and title’s match. This same method is used later for the custom fields, the array just holds the custom field text instead of post titles.

The tricky part is the image tag. the_post_thumbnail() automatically outputs an image tag, but we need to add in the title attribute I mentioned for the custom captions to work. To do this we manually grab the image path using the thumbnails ID and the internal WP function to grab the attachments image URL. Using that info we build our own image tag adding in the classes, source and title as needed.

All done. Now let’s try a custom field instead.

Custom Captions: Custom Field

Like I said I’m a sucker for an image so here is what we are going for.

Image from Castle. © ABC Studios. No infringement intended. Used for illustrative purposes only.

As you can see the text entered in the custom field is shown inside the caption box. How is this done? Well the code is nearly exactly the same as the code for using post titles. This time I’ll highlight the lines that are different between the post title code & this code.

Yep, that’s the only line you need to change. The line simply tells WordPress to grab the contents of the custom field with the key nivo_caption. So remember that nivo_caption is the key to use. You can, however, change it by altering the aforementioned text on line 9 of that code.

Updated – Custom Captions: Post Title & Post Excerpt

So you want to use both the title of the post & the excerpt inside the Nivo caption? Well normally I’d recommend you use jQuery Cycle to mix text with images in a slider, but it is possible with Nivo Slider too. First, because I’ve got a trend going, here is how it looks.

Image from Chuck Versus The Balcony (S4E11). © NBC Studios. No infringement intended. Used for illustrative purposes only.

You’ll need some CSS to get the caption to look like it does in the image. It’s pretty simple:

The caption style is a copy of the default caption style, but with the width set to 30% & the height to 100%. This changes it to go vertical instead of the normal horizontal. The H3 and P styles are for the text in the caption and can be customized to whatever you wish. One small thing to note is that you can get the caption to be on the right instead of the left by changing left: 0; to right: 0;.

Now for the code to make the caption.

As with the others the only line that is different is the highlighted one. All we do is grab the post title & the excerpt inside some HTML tags which you can feel free to change. That’s all there is to it. 🙂

That’s it. As always let me know if there is something you need help with or if you have any suggestions etc. Thanks for reading & more soon.

138 Comments

Author’s gravatar

Nice post. You are literally 1 day late from saving me from the headache of figuring this out. I used the custom fields method to get it working.

Reply
Author’s gravatar author

Damn, sorry about that Jamie. Glad you liked the post though.

Author’s gravatar

Thanks for this post. I’m trying to get my slider to show the post title as well, but haven’t been able to.For my theme I’ve added most of the code to the functions file, then some to the header. I’ve replaced the Twenty ten header with the slider.
http://pastebin.com/8vUGW4gu is my functions file
http://pastebin.com/DfzTv3bK is my header.
Is it possible to do this with the way I’ve added it?
Thanks for any info

Reply
Author’s gravatar

I figured this out minutes after posting. Thanks again for the great posts.

Reply
Author’s gravatar author

No worries. Glad it’s all sorted. Sorry about you first post being moderated. WP got a little over zealous with its spam detection.

Author’s gravatar

Thank you for figuring this out! It was such a headache trying to figure this out myself!

Reply
Author’s gravatar

Hey everyone 🙂
any ideas on how i can add the post permalink to the caption?

Reply
Author’s gravatar author

Hey Aaron,

You would just add it in the normal way. So if you code for your caption is like this:

You might change it to this:

Author’s gravatar

Hi Paul, thx for the swift response (extra kudos considering your ‘puter is down).
I had tried this method but found the_permalink() outputs as a link to the first post in the loop.

I am thinking about using a 2 dimensional array to combat this, as it would need to be outputted in the foreach loop. I will test tomorrow and post any success i have here.

Thx again, Aaron.

Author’s gravatar author

Ahh yeah sorry. Me being extremely thick. My computer is back working now, but I’m out with family so I’ll sort out the proper code for you later tonight.

Again sorry about that.

Author’s gravatar author

So here is the correction to that code. I think this should work okay.

Let me know if that works. I’ve highlighted the changed lines so you can see what needs changing easier.

Author’s gravatar

Hi Paul, that code worked just fine, i adjusted it to show a custom caption instead of the post title.

Thanks again for all your help with this,
Aaron 🙂

Author’s gravatar author

Good stuff Aaron. Thanks for coming back and sharing the code. 🙂

Author’s gravatar

any chance you could do a tutorial on getting the wordpress post or excerpt into a slider along with an image? I have been trying for weeks to get a slider to work but can’t figure it out with the post loop.

Reply
Author’s gravatar author

I’ll see what I can put together for you tomorrow. 😉

Author’s gravatar

That would be super if you could. Been searching everywhere for a way to show the post excerpt on Nivo Slider, under the Page title. Any chance you could post up the solution? Many thanks. J

Author’s gravatar author

Hey,

I meant to do that tutorial ages ago & ended up having to do some work for a client.

Nivo Slider is generally exlusively used for images. You could however place the excerpt & title into the caption. I’ll try and get something up later for you.

Author’s gravatar author

Hey JasperC,

I’ve added what you were requesting to the bottom of this post for you. It wasn’t really a large enough tutorial to warrant creating a new one.

Hope it helps you.

Author’s gravatar

Nice update to the post. I will be trying this tutorial out later today. Thanks for the tips and tricks paul

Author’s gravatar author

No problem.

I’m just sorry it took so long. I go that involved in work for a client I forgot about it when it was originally requested.

Author’s gravatar

Hi Paul,
I’ve been trying so hard to get the caption excerpt working in my slider. Thing is the slider Im using was packaged with my WordPress Theme and I think the guys who built it coded the nivo stuff differently. Is there any chance at all you would take a look at it. I’m very happy to make a donation to your site, if you’d be able to help me out on it. If not no worries. Cheers. J

Author’s gravatar

You will need to post the code in order to look at it. Do you have a working example online? what happens when you try to follow Paul’s instructions in this post?

Author’s gravatar author

Hi Jasper,

I might be able to help you out. If you’d still like me to do it you’ll have to drop me an email to admin [at] return-true [dot] com with the code you have in so I can check it’s possible to add this into it.

Thanks Jamie for helping out too. 😉

Author’s gravatar

HI Paul,

Sent on the code today. Thanks again for offering to look at it. I hope it makes sense! Jamie, cheers for the advice. Yep, I went through Pauls code, but the way I’m seeing the Nivo SLider being integrated looks quite different to Pauls. All the Divs, etc, look like they are being lined up in the .js file as opposed to within the PHP. Thanks again folks. Really appreciate it.

Author’s gravatar author

All done, as you know.

Just thought I’d better let everyone know just in case they thought I was ignoring you. 😉

Author’s gravatar

Hi Paul, for all the awesomeness that is nivo’s slider, their captions sort of disappoint. i wish there was a way to animate them in different ways.

Reply
Author’s gravatar author

I always thought the captions were a little off for Nivo, I’m no designer though so I’m not sure what they could do to make them better (other than better animations).

Author’s gravatar

Paul, what would be the best way to implement multiple sliders with different dimensions? I currently have one setup to 450px, however, I need one on the front page of my site to be around 700px.

Also, have you have any experience with all of the images showing up when the page loads? The only solution I have found was to set [lang]visibility: hidden[/lang] in the .nivoSlider img class. I thought it worked when I switched, but the images all show vertically upon page load.

Reply
Author’s gravatar author

Hi Chris,

You’d have to use is_home() to check if you were on the home page and either override the width of the nivo element or you could use a inline ternary to swap out the class. For example:

Where the class normal is 450px & home is 700px.

As for the stacking images, that is caused by the fact that Javascript hasn’t loaded yet (generally). The only real way to get around it is to make the entire Nivo element invisible (with visibility or display) via CSS & have a JS onload event swap it to visible. The problem, of course, is those with JS disabled. However if you have JS disabled Nivo won’t load correctly anyway so I’m not sure it’s much of a problem.

Does that help?

Author’s gravatar

I understand what you’re saying, but I just don’t know how to implement correctly. Unfortunately my skill sets aren’t there just yet…. Thanks for the help!

Author’s gravatar author

It’s hard to explain further without seeing exactly where it would go, but you would set up two CSS classes. The one for your 450px Nivo Slider, which I’m calling ‘normal’, and one for your 700px Nivo Slider.

Now in the div that contains your slider (in the tutorial code that’s #slider) you would add the ternary code I gave as an example. That would check to see if you are on the home page & if you are use the class with the larger width instead.

Obviously I’m assuming you are using WordPress. It’s a lot harder if you aren’t as you don’t have access to conditional functions such as is_home().

Does that help a bit more? What exactly is it you are having trouble implementing?

Author’s gravatar

Actually, that’s a really good explanation. Sometimes I just can’t wrap my head around simple things. Makes me feel pretty stupid at times… Thanks again for the help, and yes, I’m using WordPress so it’s just that simple to implement.

Here’s another question for you though. How difficult is it to add HTML to the Nivo slider? On the home page, I need a couple slides that will include buttons that link to different pages and/or external links.

Author’s gravatar author

As long as you are using the custom captions mentioned here I think you can add any HTML you like. Just remember it will only show in the caption area though.

No problem. I forget to explain in a way that everyone will understand sometimes. 😆

Author’s gravatar

I am re doing my nivo slider and I am finding that the captions work without any extra coding. I am using the featured image and when I fill out the title, it shows in the caption area. Is this normal or am I doing something wrong?

Reply
Author’s gravatar author

Hi Jamie,

No that is perfectly normal. Nivo Slider uses the title attribute of the image to create the caption. The problem is if you want to use custom captions when not using a plugin like that, or if you want to include HTML in them as it’s no really adviseable to place HTML inside an HTML tag’s attribute.

Author’s gravatar

Thanks for the updated nivo slider Paul. It works perfectly.

Reply
Author’s gravatar

Could you explain your query that you are using? I see that you set $tmp = $wp_query. When I check to make a custom query I always find that when you get to the loop, you have to use your variable like this $wp_query->have_posts()

Reply
Author’s gravatar author

That’s actually a mistake you spotted there Jamie, thanks for letting me know. I’ve changed all three snippets of code to be correct now.

Basically it’s always been my way of making sure WP is getting the results for my custom query.

The $tmp variable stores the main query and after my custom query we restore the main query as to not cause any strange happenings with our main post query.

It is perfectly valid to do it without the temporary variable & without using the object function calls. You can instead use wp_reset_postdata() at the end and it should do a similar job. I’ve just always preferred to do it like that.

Author’s gravatar

well, the code still worked fine. It returned the posts. isn’t the loop so much fun?

Reply
Author’s gravatar author

😆 Yep, the loop is always fun. That’s why I never noticed the problem until you mentioned it, it still worked on my local server, lol.

Author’s gravatar

it worked on my live server also. So that is interesting

Author’s gravatar

Paul, I have been trying to modify your code to NOT show the excerpt and title if the excerpt isn’t there. I have gone through several variations but the title always shows. I tried conditionals to test for the content and if there is content, then it should display the title and content. The idea here is that someone may not want to put in a caption. I can’t seem to figure it out. Could you take a look when you have time?

Reply
Author’s gravatar author

The code might look something like:

I think that should work. Can’t test it at the minute, sorry. You may need to change the != '' to != '[...]' as according to the WP documentation get_the_excerpt returns an empty string (if there is no excerpt), but it also says it returns an […]. I’ve never checked so you might have to try both.

Author’s gravatar

I will try it right now and let you know what happens

Author’s gravatar author

Thanks. I’d try it first, but my computer is having a disagreement with XAMPP at the minute.

Author’s gravatar

well, it was close. I have three images and I gave all three a title. The first post has to content, the second post has content, the third post has no content.

I get no caption on the first, but I do get a small black bar, so the css will need to be modified, the second and third post shows the caption for the second post. So it is close.

Author’s gravatar author

Just managed to get my localhost back up and running. Try this code instead. Seems to work for me:

Author’s gravatar

Bingo! Thanks Paul. I was just trying to track it down. I noticed that the title on the images were #caption-1
#caption0
#caption0

I was trying to figure out how to fix that. You beat me to it. How does this fix work? $add = false? I never would have tried that.

As much as this code has evolved since your original post, you might as well think about turning it into a plugin…LOL

Author’s gravatar

I got things working good now. I made one more correction to the code and I think it is perfect now. I put the images into the conditionals so that if there is an excerpt then you would be able to click on the post to read more. Otherwise, if it is just an image, then there is no link so you can’t click on the image and go to an empty post

Author’s gravatar

Oops, I didn’t enclose the code properly

Reply
Author’s gravatar author

Ahh. Good stuff. The $add variable is just used to tell if there was an excerpt. If there was one then it’s true, if not then false. Then a ternary is used to tell it whether or not to add the title attribute that Nivo uses to join the captions to the images.

Author’s gravatar

Thank you for the tips! I’ve been trying to implement them to my slider, and I’m struggling with one thing.

The nivo slider I use came with a wp pluging allowing to use categories. Then I made more changes to it, because I need two sliders on one page, each with its own size and category. Then I defined additional image sizes to be used with each of them. The first slider should use ‘slider1-post-thumbnail’ as its image. This way it keeps to its defined size even if the source image is much larger.

However, now I can’t make it work with the captions. Below, I paste the code I have now. It displays the slider in the required size, pulls posts from a category, and adds the title and excerpt.

But, it doubles every post. The first slide shows only the caption without picture, the second shows the picture without proper caption (it shows the picture slug instead). I don’t know how to make your code take the slider1-post-thumbnail as the image.

Could you have a look at it and tell me where I went wrong?

I hope I managed to paste it correctly.

Thanks in advance!

Reply
Author’s gravatar author

Hi Sylwia,

It looks as if you have doubled the image, the function the_post_thumbnail() creates an image tag so you don’t need to place it inside a one. So for example this would probably work:

I think that will work. Let me know how things go. 😉

Author’s gravatar

Thanks a lot, Paul! That worked just great. I knew I doubled the image, I didn’t know how to get rid of it without causing an error (which I did several times).

Author’s gravatar

Could I have one more question? I’m trying to make the post titles clickable. I tried the code from the comments above but that didn’t work for me.

Also, how to add the post’s categories?

OK, that’s two questions. I hope it’s not too much trouble.

Reply
Author’s gravatar

Ooops, it seems I have a more argent problem. While each of the two sliders takes thumbnails from their respective categories, the second one just copies the captions from the first one, so images are accompanied by irrelevant captions.

The code of the first slider is as above, the second one is nearly identical (which is perhaps the root of the problem):

Author’s gravatar author

Ask away. 😉

The duplicate caption problem is probably caused by the fact that the ID’s for the captions are the same for both sliders. You’ll need to change the ‘caption’ part of the id in the div on line 20 and the ‘caption’ part of the title on line 12. So you could use ‘caption2’ for example.

As for making the title clickable you would need to add an hyperlink into line 9. Like this:

To add in the category it’s a little more complicated. If we add both codes together, something like this should work:

Let me know how that works. 😉

Author’s gravatar

I got this error:

Parse error: syntax error, unexpected T_STRING in /autoinstalator/wordpress1/wp-content/plugins/wp-nivo-slider/wp-nivo-slider.php on line 302

Line 302 happens to be this one:

$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), ‘slider2-post-thumbnail’);

Which doesn’t make sense, because that line hasn’t changed.

Any ideas?

Author’s gravatar

Maybe it’s about line 311, which looks like this:

Just in case, the full php is here:

http://pastebin.com/AViPeBuR

Thanks again, Sylwia

Author’s gravatar author

Sorry about that. There is a stupid mistake in the code I gave you. If you look at the line that says:

there should be a ‘ before the ; so it should say.

Again sorry about that. I haven’t had enough coffee today. 😆

Author’s gravatar

I’m out of luck today. Now it tells me that Object of class stdClass could not be converted to string on line 298

Author’s gravatar author

Sorry. My fault again. It’s just not my day today.

Should say:

Author’s gravatar

Everything works great now! Thank you and have a great day!

Sylwia

Author’s gravatar

Hi all, i’m a WordPress webdeveloper from France.
Thanks for this excellent post !
I found another & additional way for using custom fields with WP Nivo Slider, in my case i needed to link some specific urls to my slider images, and not the permalink so here is a short code that work like a charm :

[code]

<div id="slider">
<?php
$captions = array();
$tmp = $wp_query;
$wp_query = new WP_Query(‘posts_per_page=5&category_name=Slideshow’);
if($wp_query->have_posts()) :
while($wp_query->have_posts()) :
$wp_query->the_post();
$captions[] = get_post_meta($post->ID, ‘nivo_caption’, TRUE);
$image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), ‘nivothumb’);
?>
<a href="<?php
$values = get_post_custom_values("slideurl");
if (isset($values[0])) {
?>
<?php $values = get_post_custom_values("slideurl"); echo $values[0]; ?>">
<?php } ?>"><img src="<?php echo $image[0]; ?>" class="attachment-nivothumb wp-post-image" title="#caption<?php echo count($captions)-1; ?>" alt="<?php the_title_attribute(); ?>" /></a>
<?php
endwhile;
endif;
$wp_query = $tmp;
?>
</div><!– close #slider –>

[/code]

where “slideurl” is the value for a custom link.

Thanks again and sorry for my bad english 😉

Reply
Author’s gravatar

hello..

im a newbie and im a little bit confuse here
im trying to create the Custom Captions: Post Title & Post Excerpt, but nothing happens on my theme

right now im already using a wp theme that also include with some kind of nivo slider, maybe you want to try the theme im download http://www.web2feel.com/estrada/

what should i do, if i want to create only .nivo-caption h3 on theme that already has a nivo slider?

i really appreciate your help
thanx..

Reply
Author’s gravatar author

Hi Alex,

The code for the slider in that theme is in slider.php and looks like this:

It should really be using custom captions anyway since it is extremely bad form to cram that much into a title attribute. Here is how it would look:

That should do what you are looking for.

Author’s gravatar

hey Paul..

right now im already found the main problem
i just need to combine the code and into one single line

the problem is, i dont know to do that
im already tried a few combination, like on the below, but still wont work anything

<a href="”>
<img class="slidim" src="” title=””>
<img class="slidim" src="” title=””>

is there a way i can write those code into this line?
maybe you can help me with this one Paul?

thanx..

Author’s gravatar

sorry wrong quote..

can i combine those code into one single line on img class?

Author’s gravatar author

The code I posted is the code from the theme you are using modified to show both the post title & the post excerpt in the Nivo slider caption area.

the_content_rss() has been deprecated and should no longer be used.

You cannot use the title attribute of an image to hold large amounts of text, that is why Nivo Slider provides a way for you to supply a caption from an HTML element.

Author’s gravatar

thanx for your help Paul
have a nice day..

Author’s gravatar

Awesome post man helped me out a lot – although it would be nice if NivoSlider worked a bit differently, having the HTML after the loop is a pain..

ps: Stana Katic is a hottie!

Reply
Author’s gravatar author

Glad it helped you out. It is a little bit of a pain, but the only way to do it for now.

She is. Yvonne Strahovski will always be my favourite, but I can’t deny that Stana is hot. Especially after that scene coming out of the pool in a recent episode. 😮

Author’s gravatar

fantastic tutorial,
since the advent of custom post types,post formats and taxonomies,i would appreciate greatly a nice tut on using post types with a custom metabox specifying width,height featured image src or custom url src,open in lightbox or open link to post. and of course title and caption.

i would appreciate your help significantly

Reply
Author’s gravatar author

Hi Dan,

Glad you liked the tutorial. I’m a little busy getting our new theme up and running, but that should all be finished by tonight (UK time) so I’ll see if I can make a tutorial for you tomorrow. Check back then. 😉

Author’s gravatar

What about custom field as Title and excerpt?

I’ve been trying this with no exit 🙁

$captions[] = ”.get_post_meta($post->ID, ‘caption’, true);.”.get_the_excerpt().”;

Reply
Author’s gravatar author

Hi Maryl,

I can’t see any reason for that not to work. Can you post your entire code on something like Pastebin, or if you prefer send me an email via the contact form & I’ll see if I can help you further. 😉

Older Comments

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

I'll keep your WordPress site up-to-date and working to its best.

Find out more