Troy Chaplin

Design & Development

Posted in the Blog

Create a Slideshow Using Nivo Slider and WordPress Attachments

Note: this post was originally written when I used Nivo Slider on my site. This tutorial is quite old and may not function properly with either new versions of WordPress or Nivo Slider. I would recommend taking a look at the Nivo Slider WordPress plugin.

For the work section of this site the previous theme for this site I wanted a simple slideshow to showcase my design and development work over the years, but also make it very simple to create them as a WordPress post. I was a fan of the functionality of a jQuery add-on called Nivo Slider, and thought that it would work well for what I wanted to achieve if I could incorporate it with WordPress attachments.

The end result is pretty simple: create a post, upload some images and order them, then publish. The images that have been attached to the post will be put into a slideshow which you can modify with a few simple edits to Nivo Sliders options. The sizes of the images also conform to what you have specified in the media settings in the WordPress dashboard, so you should take that into consideration when planning your slideshow.

Let’s take a look at how I’ve set this up for my work portfolio you can set this up.

Note: any reference to this being active on my site no longer apply, this post was written while using another theme which has since been replaced.

Adding jQuery and Nivo Slider to Your Theme

First off, you need to download jQuery and Nivo Slider. I would recommend reading through the usage documentation for Nivo Slider, and maybe building an HTML example to see how it all works.

After downloading and copying the scripts into my theme folder, I added it to the footer right before the closing body and html tags. There are quite a few options available to customize how Nivo Slider acts, try them out and see what works for you. The following code is how I have things setup. Be sure to change the FILELOCATION and DIVNAME in two areas to match up with the path to your scripts as well as the div that your slideshow will be placed within.


<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/FILELOCATION/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="<?php bloginfo('template_directory'); ?>/FILELOCATION/jquery.nivo.slider.pack.js"></script>

<script type="text/javascript">
	$(window).load(function() {
		var total = $('#DIVNAME img').length;
		var rand = Math.floor(Math.random()*total);
		
		$('#DIVNAME').nivoSlider({
			effect:'fade', //Specify sets like: 'fold,fade,sliceDown'
			animSpeed:800, //Slide transition speed
			pauseTime:8000,
			directionNav:false, //Next and Prev
			controlNav:false, //1,2,3...
			pauseOnHover:false, //Stop animation while hovering
			captionOpacity:1, //Universal caption opacity
			startSlide:rand
		});
	});
</script>

Creating the Function

Once you have the two scripts added into your footer.php file we can create the function need. This can be added into your functions.php file, or directly into the page or post template that you want to use your slideshows.


<?php
	// get all of the images attached to the current post
	function nivo_get_images($size = 'large', $limit = '0', $offset = '0') {
		global $post;
		$images = get_children(
			array(
				'post_parent' => $post->ID,
				'post_status' => 'inherit',
				'post_type' => 'attachment',
				'post_mime_type' => 'image',
				'order' => 'ASC',
				'orderby' => 'menu_order ID'
			)
		);
		if ($images) {
			$num_of_images = count($images);
			if ($offset > 0) : $start = $offset--; else : $start = 0; endif;
			if ($limit > 0) : $stop = $limit+$start; else : $stop = $num_of_images; endif;
			$i = 0;
				foreach ($images as $image) {
				if ($start <= $i and $i < $stop) {
					$img_title = $image->post_title;   // title.
					$img_description = $image->post_content; // description.
					$img_caption = $image->post_excerpt; // caption.
					$img_url = wp_get_attachment_url($image->ID); // url of the full size image.
					$preview_array = image_downsize( $image->ID, $size );
					$img_preview = $preview_array[0]; // thumbnail or medium image to use for preview.
					// This is where you'd create your custom image/link/whatever tag using the variables above.
					// This is an example of a basic image tag using this method.
					echo '<img src="' . $img_preview . '" alt="<?php echo $img_caption; ?>" />';
					// End custom image tag. Do not edit below here.
				}
			$i++;
			}
		}
	}
?>

Adding the Slideshow to Your Template

Once you have created the function, all that’s left to do is add a small line of php into the area in which you want your slideshow to appear. You can set the size of the image by replacing ‘large’ in the example with ‘medium’ or ‘thumb’ and it will resize based on your media settings.


<?php nivo_get_images('large','0','0'); ?>

Once you have all of this done, you should be able to create a new post or page, and when uploading images, drag and drop them into your preferred order, give them title or alt tags, and let the scripts and functions handle the rest.

UPDATE: Styling the Slideshow with CSS

I realized late last night that I completely forgot to add the styling. If you had gone through the usage documentation on the Nivo Slider website you would have gone through this step already. If not, here’s an example of the simple CSS that I use for my slideshow. The third item (#DIVNAME img) is used to prevent all the images from displaying as the page loads, and adds a loading image, which you can replace with your own customized animated GIF.


#DIVNAME-bg {
	margin-top:8px;
	padding:5px;
	background-image:url(PATHTOTHEMEIMAGES/filename.png);
	background-repeat:repeat;
}

#DIVNAME {
	width:620px;
	height:620px;
}

#DIVNAME img {
	display:none;
	background:url(PATHTONIVOIMAGES/loading.gif) no-repeat 50% 50%
}

15 Comments

  1. Posted February 23, 2011 at 10:53 am | Permalink

    man, that’s just awesome! I was searchin’ all over the place for some piece of code making wp-attachements work with nivo slider in an easy way, specially for people using only the visual editor mode.

    THANK YOU :)

  2. Posted March 1, 2011 at 4:09 am | Permalink

    hey, after working a bit with the code I found that it also includes the posts featured image in the slideshow – any way to exclude the featured images specifically from the slides and just show images/attachements from the content?
    thx, nico

  3. Posted March 1, 2011 at 4:17 am | Permalink

    ok, you can exclude the featured images/thumbs by adding the following to the images-array : )

    ‘exclude’ => get_post_thumbnail_id()

    thanks again!

    • Posted March 1, 2011 at 6:40 am | Permalink

      Thanks for the addition Nico! I never tried it while using featured images, but I think I may do so with a new project I’m working on.

  4. Caleb Jacob
    Posted March 29, 2011 at 7:26 pm | Permalink

    Thanks so much for this tutorial!!! It was EXACTLY what I was looking for. Took me a couple tries – not sure what I was doing wrong at first. But I got it working now :)

    Thanks again!

    -Caleb

  5. Posted April 11, 2011 at 4:15 pm | Permalink

    Thanks for this. I found this tutorial really useful

  6. Serafim
    Posted May 14, 2011 at 2:47 pm | Permalink

    Hello.

    Wanna ask you if it si possible to have the sidebar widget working without adding images to posts.

    Maybe getting pictures from posts through a Category or Tag.

    Thank you.

    • Posted May 26, 2011 at 6:39 am | Permalink

      Hi Serafim,

      Not sure about using this within a sidebar widgets, I haven’t really tried it this way. Instead of getting images through a Category or Tag, I would suggest creating a custom post type for images, where images attached to a post there could be pulled out and placed on any page.

  7. Posted May 26, 2011 at 6:17 am | Permalink

    Hi
    Great post!
    I am having tremendous difficulty adding NivoSlider to my WordPress theme.
    No matter what code I add or where I put it this isn’t working for me.
    Your coding is even more complex than the normal install & if I can steel myself I shall give it a try.
    I would like to get this NivoSlider working in my theme.
    Many thanks for this great tutorial.

    • Posted May 26, 2011 at 6:43 am | Permalink

      Sorry if you find this complex Richard. My suggestion would be to build a slideshow using the default Nivo installation method to make sure it functions properly, then walking through this tutorial once more.

      The key thing to remember is adding the JS calls and function into the footer, the second bit of code in the functions.php file. The nivo_get_images php snippet can then be added to any page where you want it to appear.

  8. debra
    Posted September 5, 2011 at 7:31 pm | Permalink

    hi troy,
    i installed and activated the easy nivo slider plugin right from my wordpress dashboard. do i still have to add all of the code in order to get it to work? i am new to coding and find this confusing plus i do not know where to go on my dashboard to put it in. (i.e…footer code, functions php file etc,) all of the things you’ve mentioned are foreign to me….help please!!!!

    ps…i am currently using nextgen which is fine but i want to center the slideshow in my content area and can’t seem to do that!

    • Posted September 17, 2011 at 11:52 am | Permalink

      HI Debra, none of the above tutorial will apply if you are using the Nivo plugin for WordPress. I would recommend reading more about using the plugin in the Nivo Support Forums

  9. c1987
    Posted January 17, 2012 at 2:31 pm | Permalink

    Question!

    Thanks for your awsome code, it works nice, but i wanted to ask you this:

    How can you turn this function into an shortcode? How can you change:

    Into a [nivo_gallery] shortcode, that would still display all the images attached to the post, but you don’t have to hardcode it into single.php or post.php?

  10. Tanya
    Posted June 12, 2012 at 8:49 pm | Permalink

    Hi, I just create the function in my site, but it gives me an error in the console “$(“#nivoImage”).nivoSlider is not a function”
    It tottaly drive me crazy, I cannot find the error. I follow all the steps in this tutorial (by the way, you have a few errors, like the url in the php.net site and different functions names! grounge_get_images and nivo_get_images!) but cannot find the explanation for this issue.
    Can you please look the code? this is my site: http://travailderue.net/info/adhesion/

    Thanks!!!

    • troychaplin
      Posted June 12, 2012 at 9:18 pm | Permalink

      Thanks for pointing out the errors. I just updated them, I guess I missed a couple of errors as I was migrating the old site into this new one.

      As far as your errors go, I see no reference to the function or even the use of the Nivo Slider script in your source code.

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>