Build a Slideshow Plugin for WordPress

Build a Slideshow Plugin for WordPress

Tutorial Details
  • Version: WordPress 3.1+
  • Difficulty: Easy
  • Estimated Completion Time: 1 hour

Integrating slideshow functionality into WordPress is a highly required feature for almost any theme, but how hard is it to include and how flexible is it? In this tutorial we are going to, in different ways, include one of the most popular and used jQuery slideshows, Nivo Slider.

There is, actually, already a coded WordPress plugin for the Nivo Slider, right on the official Nivo Slider page. But we are going to build one in this tutorial anyway, and we are most definitely going to do it differently. In this tutorial we are going to create a Nivo slider plugin that will have widget functionality, short code functionality and you will even be able to integrate it as a simple function call and hard-code it into your theme where ever the user wishes.

By following this tutorial, it is implied that you are running an Apache and MySQL server locally or remotely in order to be able to install WordPress. Also, that you have a 3.1+ version of WordPress installed that you have access to its file system, and that you have basic PHP, CSS, JavaScript and HTML knowledge.


Step 1 Creating the Plugin

One of the easiest parts of this tutorial. We are going to create a folder named nivoplugin inside the wp-content/plugins directory inside your WordPress installation. Inside that directory we will create a nivoplugin.php file with the following code:

<?php
/*
	Plugin Name: Nivo Plugin
	Description: Simple implementation of a nivo slideshow into WordPress
	Author: Ciprian Turcu
	Version: 1.0
*/
?>

This is the basic plugin information used by WordPress to identify the plugin name and details. Things like Plugin Name, Description, Author and Plugin version are required parameters that are added as commented text at the top of each plugin so that WordPress can identify the plugin, manage it, run it and show the required information about it in the plugins page.

“For more information on plugin header text and other options that can be added to it please read Writing a Plugin in the WordPress Codex.”


Step 2 Creating the Admin Slideshow Management Functionality

The slideshow is made out of pictures, so in order to make a simple implementation of the jQuery Nivo Slider we need a way to add and manage pictures in the admin panel. Our approach is going to make good use of the custom post type WordPress functionality. Custom post types will be used to create a new custom page where each post contains all the required image details: the name and of course the most important part, the image itself. We are going to use the title and editor for the name and description information and the featured image functionality to upload the picture, manage and identify it.

function np_init() {
	$args = array(
		'public' => true,
		'label' => 'Nivo Images',
		'supports' => array(
			'title',
			'thumbnail'
		)
	);
	register_post_type('np_images', $args);
}
add_action('init', 'np_init');

In the above example we are adding a hook to the np_init function using the init hook tag that will run before the headers run. We need to do this so we can then include inside the register_post_type function with its parameters. This function is the function used to add and manage a new custom post type. Basically we include a new custom post type named np_images with some arguments.

The arguments are an array of values that represent the settings of that new custom post type. Things like if it is intended to be used publicly, we set public to true, we give it a label with the name Nivo Images and we set the fact that each post has a title and a featured image with the variables title and thumbnail as an array to the main attribute supports.

This creates the custom post type and it looks like this:

At this point we have a registered and working custom post type by the name of np_images. We can add new posts, delete them, and edit them as with regular posts, but custom made for our purpose to manage images for the slideshow. Basically this is the place where we add pictures for the Nivo slideshow as posts.


Step 3 Including the Nivo Slider Scripts and Styles

This might sound like something slightly complicated or time consuming a little more than usual. It’s not. We are going to download the free jQuery version of the Nivo Slider and include its necessary scripts and styles so that we may later use them with some custom code and images.

To download the sources we will go to the Pricing page on nivo.dev7studios.com and click on the jQuery Plugin (Free version) Download button on the left to download the sources.

For the purposes of this tutorial, we are going to keep things very simple. We unzip the file and include the whole directory inside our plugin directory. Inside the nivo-slider folder we have another folder named demo. We are going to delete that as we have no use for it and we don’t want a cluttered plugin with unnecessary stuff in it.

Registering and Including Scripts and Styles

The next part of this step is including the necessary Nivo Slider files. In our nivoplugin.php file we will add the following:

add_action('wp_print_scripts', 'np_register_scripts');
add_action('wp_print_styles', 'np_register_styles');

This is going to hook to some functions (the second parameter is the function name). We need these hooks to properly include the scripts and styles into the front-end. Let’s look at the callback functions of our previous hooks.

function np_register_scripts() {
	if (!is_admin()) {
		// register
		wp_register_script('np_nivo-script', plugins_url('nivo-slider/jquery.nivo.slider.js', __FILE__), array( 'jquery' ));
		wp_register_script('np_script', plugins_url('script.js', __FILE__));

		// enqueue
		wp_enqueue_script('np_nivo-script');
		wp_enqueue_script('np_script');
	}
}

function np_register_styles() {
	// register
	wp_register_style('np_styles', plugins_url('nivo-slider/nivo-slider.css', __FILE__));
	wp_register_style('np_styles_theme', plugins_url('nivo-slider/themes/default/default.css', __FILE__));

	// enqueue
	wp_enqueue_style('np_styles');
	wp_enqueue_style('np_styles_theme');
}

The script callback function registers and includes 3 important javascript files: jQuery (as a dependancy of Nivo Slider), nivo-slider base file (jquery.nivo.slider.js) and our custom script file (script.js). Nivo Slider requires jQuery to work and we need a custom script to activate it.

The script.js File:

jQuery(document).ready(function($) {
	$('#slider').nivoSlider();
});

The script is pretty simple, it requires jQuery to attach the nivoSlider function to the tag with the id of slider. That tag is going to take the nivo-slider properties and functionality.

Lastly in our previous step, the style callback function registers and includes 2 more important files: the nivo-slider.css file that has all the styles needed to make the slider look and work accordingly, and a default.css file inside the themes/default folder that we use to theme the slideshow with the default nivo-slider theme.


Step 4 New Image Sizes

As mentioned in the beginning, this tutorial is going to cover the implementation of a widget, a shortcode and a function for hard-coding the slider if needed by using the plugin we are building. For the shortcode and function we need pretty much the same image sizes and for the widget a smaller size for the height and width of the images.

First, we must take into consideration the fact that we are using featured images in custom posts for our slideshow images. So how do we resize and crop those pictures to fit our required needs? We are going to add new image sizes that WordPress will resize and crop to on each new image upload. To add the new image sizes we will use the add_image_size function by adding the following code inside the np_init function:

	add_image_size('np_widget', 180, 100, true);
	add_image_size('np_function', 600, 280, true);

In the above source code we implemented 2 image sizes that we will call later on using the names np_widget for widget and np_function for shortcode and PHP function to identify them.

One More Thing

In order to enable post thumbnails in the plugin the following line of code needs to be added in our plugin. We are going to add it above the add_action lines.

	add_theme_support( 'post-thumbnails' );

“Image sizes added with add_image_size will only work for new pictures that are uploaded after the function is activated.”


Step 5 The PHP Function

One of the main features of the plugin is a PHP function that you can use anywhere in your theme code to insert the large 600×280 Nivo slideshow.

Because we are using custom posts to manage our pictures for the slideshow, we need to query those posts and get the titles and pictures from the custom post type. For that we are going to use a new WP_Query loop with the parameters of the $args variable that selects the custom post type and creates a slideshow of maximum 5 images from the query. Next we create a variable $result that has all the HTML code needed for the Nivo slideshow. We are using the demo HTML code wrappers from our Nivo script download folder.

function np_function($type='np_function') {
	$args = array(
		'post_type' => 'np_images',
		'posts_per_page' => 5
	);
	$result = '<div class="slider-wrapper theme-default">';
	$result .= '<div id="slider" class="nivoSlider">';

	//the loop
	$loop = new WP_Query($args);
	while ($loop->have_posts()) {
		$loop->the_post();

		$the_url = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), $type);
		$result .='<img title="'.get_the_title().'" src="' . $the_url[0] . '" data-thumb="' . $the_url[0] . '" alt=""/>';
	}
	$result .= '</div>';
	$result .='<div id = "htmlcaption" class = "nivo-html-caption">';
	$result .='<strong>This</strong> is an example of a <em>HTML</em> caption with <a href = "#">a link</a>.';
	$result .='</div>';
	$result .='</div>';
	return $result;
}

Inside the loop we are using the wp_get_attachment_image_src function to retrieve the featured image from our custom post. We use the np_function value for the size of the image that we previously added in np_init. Because we are inside the loop, we can use $post->ID to identify the post. The function has one parameter, $type, that is used to set the images size from wp_get_attachment_image_src with one of the previously set image sizes. The variable has the default value of np_function. If no parameter is given when calling the function the default variable will kick in.

The titles of the posts are added as values to the title HTML parameter of the image tag and are visible at the bottom of the image slideshow as floating text over the images inside a transparent dark background.

The slider is automatically resized like the image sizes inside it, so whatever image sizes we use, we are going to have a slideshow of that size.

The slideshow in the np_function size looks like this:

This preview of the slideshow is the shortcode implementation that will be covered next.


Step 6 The Shortcode

Another main feature is the shortcode implementation. This is actually extremely easy to implement and can be done with one line of code. Just add this line in the np_init function above everything that is in there already:

	add_shortcode('np-shortcode', 'np_function');

The shortcode hook will actually use our PHP function to return the contents of the slideshow. That is all, very simple and fast implementation of the shortcode. To use it, just add [np-shortcode] in the content of any post or page. That text will be replaced with the actual slideshow.


Step 7 Building the Widget

In this step we are going to build a simple widget that will have the sole purpose of showing a small slideshow in the sidebar where ever it is placed.

We already have the size set for it in step 4 and we have all the other functionality that includes and generates the Nivo slideshow that we can use to integrate into the widget. So all that remains now is to build the widget and integrate the previous code.

function np_widgets_init() {
	register_widget('np_Widget');
}

add_action('widgets_init', 'np_widgets_init');

In this first part we are going to implement a new hook that you should add amongst the others. This hook uses the widgets_init tag and uses a function that we are going to name np_widgets_init. This function runs when the widgets are created. As a result we are going to register the widget under the name of np_Widget as in the example above.

The Class

To create a new widget, we are implementing a new class named np_Widget that extends the WP_Widget class. As a first function the __construct is the primary and most important function of the class and of our widget functionality. The function has parameters that we use to give the widget an unique ID that in our case is named np_widget, a name, Nivo Slideshow, and even a description as the following code shows:

class np_Widget extends WP_Widget {

	public function __construct() {
		parent::__construct('np_Widget', 'Nivo Slideshow', array('description' => __('A Nivo Slideshow Widget', 'text_domain')));
	}
}

This is of course just the start of our widget, there are a few other functions we need to implement and configure as we need them to work.

Widget Backend

The widget looks as any other widget in the back end. We need to give the widget a title that has the possibility to be input by the user and later saved by the plugin. To do this we need to write the form function extended from the WP_Widget class. In this function we are going to use the $instance parameter that the function provides to get the title which is a variable later implemented, saved and updated. So we create the form input element using the following code:

	public function form($instance) {
		if (isset($instance['title'])) {
			$title = $instance['title'];
		}
		else {
			$title = __('Widget Slideshow', 'text_domain');
		}
		?>
			<p>
				<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
				<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo esc_attr($title); ?>" />
			</p>
		<?php
	}

This code runs only in the back end and is required by the following functions in order to submit the title name for saving and later use in the front end. The $instance variable has the value of the title and is used directly like the above example with no other query or function call.

Saving the Data

After the form is submitted from the previous function it needs to be processed and saved. This is done in the update function that we also need to add to the class with the following code:

	public function update($new_instance, $old_instance) {
		$instance = array();
		$instance['title'] = strip_tags($new_instance['title']);

		return $instance;
	}

The value of the field is passed through the $new_instance variable that is stripped of tags, inserted in the $instance variable so that it can be returned by the function and saved by WordPress as part of its extended widget functionality.

Widget Front-End

Last but not least, another very important and also representative part of our widget is the front end functionality. Obviously, every piece is important for the end result to work, but this part is what you see in your theme.

The widget function is managing the front end of the widget and has two parameters: $args and $instance. The $args parameter is used to get variables like $before_widget, $after_widget and $before_title, $after_title that we are going to use in our implemented code. The widget function looks like this:

	public function widget($args, $instance) {
		extract($args);
		// the title
		$title = apply_filters('widget_title', $instance['title']);
		echo $before_widget;
		if (!empty($title))
			echo $before_title . $title . $after_title;
		echo np_function('np_widget');
		echo $after_widget;
	}

To implement the slideshow we are using the function np_function but in this case we are giving it the parameter np_widget so that we get the image sizes we want for the widget.

This covers the widget implementation of the Nivo Slider in our plugin. At this point you can go into the admin panel and add a few posts in the Nivo images menu and attach featured images to them so that they appear in the slideshow.

“For more information about WordPress Widgets API check the WordPress Codex Widgets API.”


Conclusion

It’s very easy and fast to implement a slideshow in WordPress if you know what you are doing and especially if the slideshow functionality is already built and you are just integrating it. Still you have to be careful not to use some functionality that’s already there and of course, it’s easy if you implement it in a very basic manner like we just did, as a more flexible approach with many options and features might complicate things a little, depending on what the features are.

Ciprian Turcu is CiprianTurcu on Themeforest
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://www.lebloggeR.com Soufiane

    A demo link is always needed!

  • http://www.leachcreative.com Andrew

    Pretty awesome tutorial, I definitely liked that you made a widget version of it. Thanks for sharing.

  • Pingback: Build a Slideshow Plugin for WordPress | Qtiva

  • mihai

    agree with soufiane…Cipri, show us the demo:)

  • Pingback: This Week In WordPress: Jun 25, 2012 | Max Foundry

  • Sebastian

    The images doesnt show , im using 3.4 WordPress, also i tested on previous version.

    • http://www.ciapci.com Ciprian Turu
      Author

      Hi,

      Like I said in the tutorial, it only works with new images father you add the add_image_size functionality. Cheers!

  • http://www.adamcrooker.com AdamTheGr8

    Very – cool. I’ve been doing my own custom sliders for WP for a while now and this will help take it to the finalized level I’ve been looking for. Thanks bunch!

  • dj

    i don’t think this kind of tutorial should never be published without a demo link.

  • http://joejoiner.tk Joe

    I notice that we add extra image sizes in the code, but when I set the featured image, WordPress automatically chooses the full-size original version of the image. It has been cropped and renamed to the respective sizes in /wp-content/uploads, but the slider uses the original causing the height of the slider to stretch. I tried with your nivoplugin.php, but I got the same result. Do I need to add something to the code, or am I just missing the point? Thanks.

  • http://bdgeeks.com foysal

    Awesome! Exactly what I was looking for! grateful to you man!Can’t thank you enough and I totally agree with andrew that you did a good job making it as an widget too! although a demo would have been cool! Nevertheless Thanks a bunch.
    word of gratitude from Italy.

  • http://www.ciapci.com Ciprian
    Author

    Hi guys, thanks for the feedback and appreciation.

    As for the demo, you have the source files, install them and there’s your demo.

    Cheers!

    • http://www.mojowill.com themojowill

      Fail

      • http://wp.envato.com/ Japh Thomson
        Staff

        Sorry, Will, at the moment we don’t provide hosting for author’s to put their demos on, so not all articles have demos.

        Ciprian possibly could’ve worded his comment a little more sympathetically, but he does have a point. If there’s no demo, but there are downloadable source files, then it’s fairly simple for you to setup a demo of your own! :)

        • http://wpbaseju.mp Piet

          Although you have a point Japh, the whole purpose of a demo for most people is to see the plugin/function in action and then decide whether it is worth to download it and install it and trying to get it to work.

          To suggest to interested people to download and install it, will most likely result in a lot less people downloading and installing it for the simple reason that there are many many sources available that actually have a demo…

          It could be worth your while to give each author a little space for demo-ing his function…

          • http://wp.envato.com/ Japh Thomson
            Staff

            Good suggestion, Piet. Thank you for your thoughts :)

  • zetoun

    Thanks for this tutorial,
    here some tips :

    1) register your javascript with “wp_enqueue_scripts” and put JS to the footer

    function np_register_scripts() {
    wp_register_script(‘np_nivo-script’, plugins_url(‘nivo-slider/jquery.nivo.slider.js’, __FILE__), array( ‘jquery’ ),true);
    // add dependency to np_script with np_nivo_script
    wp_register_script(‘np_script’, plugins_url(‘script.js’, __FILE__),array(‘np_nivo-script’),true);
    }
    add_action(‘wp_enqueue_scripts’, ‘np_register_scripts’);

    2) enqueue javascript ONLY if the page display the slideshow
    eg:
    function np_function($type=’np_function’) {

    // add the javascript when displaying the slideshow
    wp_enqueue_script(‘np_script’);
    }

    • http://www.ciapci.com Ciprian
      Author

      Hey, thank you!

  • Pingback: Build a Slideshow Plugin for WordPress | Wptuts+ » Web Design

  • http://prop-14.com Randy

    It’s funny, I “just” had changed the way I did my slideshows to make it easier for my clients to manage. I also used a custom post type, the difference being, I used “each post” as a complete gallery with all attached images as the collection of slides.

    This way, the user could:
    - easily rearrange the images
    - upload any number of images
    - manage multiple slideshows (which is what prompted me to do this)
    - set a featured image that represented the collection of slides
    - cretae a description about the slides using the main content area
    - use short code to embed any slideshow into any page(s) or widget
    - I also had an extra field in the media uploader to include a link destination for each image

    Just thought I’d mention for anyone wanting to try a variation of your gallery.

    Cool post!

    • http://www.ciapci.com Ciprian
      Author

      Interesting approach, that is something I want to test out, maybe a future tutorial involving that might be useful even just as an idea, thanks!

      And thank you for appreciating the tutorial!

    • http://maddisondesigns.com Anthony Hortin

      Great post Ciprian. Thanks. The use of Custom Post Types really opens up the what you can do with WordPress!

      Randy, Some really good suggestions you’ve made there to make this even more flexible. Great job!

  • Abe

    Thank you so much for this tutorial!

    The timing on this tutorial is perfect as I was trying to create my own custom plugin of the Nivo Slider jQuery plugin, but got stuck with the creating the admin section.

    I like how you covered a lot of ground with this tutorial. Keep up the good work!
    This tutorial helped a beginner like me get a much clearer understanding of how to develop plugins.

    I think this tutorial is great because it goes beyond the simple “Hello World!” style plugin development tutorials.

    Once again, thank you!

  • Pingback: Membuat sendiri plugin slideshow di wordpress | circlecode

  • Pingback: Expand2Web and Cashie Commerce Launch Integrated Solution for Creating … | Open Knowledge

  • Pingback: Tweet-Parade (no.26 June 2012) | gonzoblog.nl

  • jkd

    I am confused, what happen to flexslider slider tutorials?

  • jeet

    i want to change my easing sliders images with change in categories like
    if i clicked on cars then it will show car images if clicked on nature then show natures related images
    plz give some tricks to do this

  • Toast

    How do I use the slider outside of a post or page (I want it to be in a static place on a particular page) and the shortcode doesn’t work.

    • http://wp.envato.com/ Japh Thomson
      Staff

      Hey Toast, you can use a shortcode outside of a post/page with the do_shortcode() function, as referenced in the WordPress Codex.

      Hope that helps you on your way :)

      • Toast

        Thanks!

  • Jay

    Is it possible to change the location of the uploads=ed files? Maybe using wp_handle_upload? I need a different directory then wp_content/uploads/

    Thanks for the tut.

  • Jean

    Is there a way to add the image caption or a post excerpt to this? I need a way for the client to add a lengthier caption beyond just the post title, preferably that I can style to look the way our designer intended. I’ve been googling my rear-end off about this and I’m stumped.

    • Jean

      Well, I figured out this much: to add the excerpt field to the plugin dashboard, just add ‘excerpt’ to the supports array in the np_init function — so it looks like this:

      function np_init() {
      add_shortcode(‘np-shortcode’, ‘np_function’);

      add_image_size(‘np_widget’, 180, 100, true);
      //add_image_size(‘np_function’, 936, 339, true);

      $args = array(
      ‘public’ => true,
      ‘label’ => ‘Nivo Images’,
      ‘supports’ => array(
      ‘title’,
      ‘thumbnail’,
      ‘excerpt’
      )
      );
      register_post_type(‘np_images’, $args);
      }

      But I can’t figure out how to get the excerpt to display as part of the slide caption. All of my attempts just cause the slider to collapse between slides.

      • Jean

        Got it. After much trial and error, I finally just tried adding get_the_excerpt() after get_the_title() in the loop, and it actually worked. I can’t believe it turned out to be that simple. So this is what I ended up with:

        $result .=”;

        • Ricardo Pinto

          Hi Jean, I to need to place the excerpt field, but I can not display them in the slides, How did you do it?

  • Jesper

    you may also use this

    $result .= get_post( get_post_thumbnail_id() )->post_excerpt;

    it should display your caption

  • Pingback: Word-press plugin development links « dineshshrivastava

  • chakri

    Thank you, very nice post.

  • clarencelouie

    Can you help me in converting this slider to a wordpress plugin? http://demo.tutorialzine.com/2012/02/css3-product-showcase/#/intro Thanks :)

  • suresh

    it is showing latest image only what is the problem please help me

    • ivan

      Same problem… Slider works only in widget mode (without transition effects) :/

    • ivan

      Working fine when post shortcode in text editor (not visual)

  • Pingback: Responsive Web Design JamesDoesDesign.com | James Myers Does DesignJames Does Design

  • ivan

    How can I change the theme of Nivo slider???

    • ChapDaddy65

      download the jQuery version from dev7 [http://dev7studios.com/downloads/63] then copy and paste the theme folder into the plugin’s theme folder. Then do a find and replace in [nivoplugin.php] and swap out the word ‘default’ with whichever theme you want to use. Worked for me :)

  • Habib

    best for learning…
    lot of thanks

  • Pingback: 30 Useful Tutorials to Create WordPress Plugin | Doublemesh

  • chinmoy debnath

    This is a great tutorial…very helpful

  • Pingback: 20 Useful WordPress Theme Tutorials and Resources - Streetsmash

  • Pingback: The MegaList of WordPress Resources - Part 3

  • Pingback: The MegaList of WordPress Resources – Part 3 | Hosting Reviews

  • andresabello

    How can you make this plugin so that you can add multiple slideshows?

  • ybp

    Hello!
    I would to know how can we make this kind of plugin for text (post text) content?
    Tank you=

  • ChapDaddy65

    Having the same problem as @disqus_VZHsdLAYWe:disqus . I added used “” to embed the slider into my homepage and I have 5 slides, all with text and a photo on each slide and it only shows the latest post I made and nothing else. Why cant I see the nav arrows or move my slider?

  • http://noaneo.fr/ noaneo

    hello,
    how to make the plugin work with “the_post_thumbnail” items already created.
    thank you