Try Tuts+ Premium, Get Cash Back!
Building a Client Testimonials Slider Plugin

Building a Client Testimonials Slider Plugin

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

Nowadays image sliders are the trend and you can see them in every other site. That said, sliding stock photos, even with the most advanced and beautiful animations, don’t really build any trust in your customers. A better approach would be to use customer testimonials in our slider. With proper styling this method could be just as visually engaging and makes the user more confident in using (and buying) your product than showing them random stock photos.

“…sliding stock photos … don’t really build any trust in your customers.”

We are going to create a client testimonial slider. You will be able to add new client testimonials in the admin, and show them on your website through shortcodes. For sliding the testimonials we will use the free SlideJS jQuery plugin. This way you will have higher control of the animation and effects.


Step 1 Creating the Plugin

We want the new feature as a plugin, so we can use it with any themes. To do this first we create a new folder called testimonialslider in the wp-content/plugins folder ( I’m assuming here that you have WordPress already installed ).

Next create a new .php file in it. Let’s call it testimonialplugin.php and write some comments in it so WordPress recognizes it as a plugin.

	<?php
	/*
		Plugin Name: Client Testimonial Sliders
		Description: Sliding client testimonials with SlideJS
		Author: Richárd Ötvös
		Version: 1.0
	*/
	?>

You can give a lot more information than this ( as you can see in the Plugins section of the WordPress Codex ), but for our purpose this is enough. With these few lines you will be able to see your plugin and activate it through the WordPress plugin manager. So let’s do just that and activate it.


Step 2 Creating the Client Testimonials Post Type

If you want to add testimonials in an user friendly way, your best bet is to do that with custom post types. Because the testimonials won’t be stand alone posts, we won’t use every functionality, just what is necessary for our purpose.

Add this code to our testimonialplugin.php file (before the closing PHP tag)

	function testimonials_init() {
		$args = array(
			'public' => true,
			'label' => 'Client Testimonials',
			'supports' => array(
				'title',
				'editor',
				'custom-fields'
			)
		);
		register_post_type('testimonials', $args);
	}

	add_action('init', 'testimonials_init');

In the testimonials_init() function we first set some parameters for our post type. We want it to be public, and also to be called “Client Testimonials”. The support part of the array might be a little bit confusing. It says that we want our post type to have a title and also the editor where we can write our content. But why do we want to support custom post types?

So that your users don’t have to learn any special mark-up if they want to add the name of the client or possibly a homepage!

Making your interface user-friendly is very important when using CMS’s, as user friendliness is one of the main reasons why you are using WordPress.


Step 3 Creating the Name and Link Custom Fields

As I said, providing custom fields for your custom values make your plugin much more user friendly. Here you can choose from a few options:

  • Using some special markup
  • Using custom fields the normal way
  • Using default custom fields
  • Using metaboxes
  • Using some custom field plugin

I might write about these options in another tutorial, but basically the first two options are not really user friendly. Creating metaboxes, while not that hard, takes up some time so we go with the third option and add some default custom field boxes.

Add these lines after the previous code block:

	function set_testimonial_custom_fields($post_id) {
		if ( $_GET['post_type'] == 'testimonials' ) {

			add_post_meta($post_id, 'Client Name', '', true);
			add_post_meta($post_id, 'Link', '', true);

		}

		return true;
	}

	add_action('wp_insert_post', 'set_testimonial_custom_fields');

In the set_testimonial_custom_fields() function we first check if we are creating a post of type ‘testimonials‘. If we do, then we are using the add_post_meta() WordPress function to add a custom field. The first parameter is the ID of the post we are creating, the second is the name of the custom field, the third is the default value of the custom field (here we are using an empty string), and the fourth is a boolean value which decides if the field is unique. If set true that means that you can only have one of these fields per post.

With this code you can easily extend the plugin and add even more extra fields to the testimonials post type.


Step 4 Registering the Slide.JS Script

I mentioned in the overview that we are going to use the jQuery plugin Slide.JS to slide our testimonials. To do that we should include the script in our plugin.

Downloading Slide.js

First head to the SlideJS hompage and download it. If you want to do some extra customization on your slideshow, you might want to bookmark the docs page, as you can read the documentation of the plugin there.

So, after you downloaded the .zip file, extract it. Go to the Slides/source folder (in the .zip file) and extract the file slides.min.jquery.js to your plugin folder. You might want to create a js folder in your plugin directory to save it in so all of your JavaScript files will be in one place.

Adding the Script to Our Plugin

Now let’s tell WordPress to include our scripts if our plugin is active

	// Adding the Slide.js script and our script
	function testimonials_register_scripts() {
		// Only add these script if we are not in the admin dashboard
		if (!is_admin()) {
			// Registering scripts
			wp_register_script('testimonials_slide_js', plugins_url('js/slides.min.jquery.js', __FILE__), array('jquery') );
			wp_register_script('testimonials_script', plugins_url('js/script.js', __FILE__), array('jquery') );

			// Enqueing scripts
			wp_enqueue_script('testimonials_slide_js');
			wp_enqueue_script('testimonials_script');
		}
	}

	add_action('wp_print_scripts', 'testimonials_register_scripts');

We are using the wp_print_scripts hook to add the scripts to the head of the pages. In the testimonials_register_scripts function we are first registering, then enqueuing the scripts. Here are some things to look out for…

“…you should only load the scripts (and styles) that you need”

We’re using the conditional tag with the is_admin() WordPress function and only add the script to the head if we are not in the administration dashboard. It is a small optimization. Basically you should only load the scripts (and styles) that you need, and only when you need them.

When we’re using the wp_register_script() function to register our slides.min.jquery.js plugin, we set jQuery as a dependency, so they will be loaded in the correct order. Last, don’t worry about the script.js file yet, we will create it shortly.


Step 5 Displaying the Testimonials

Now let’s display our testimonials! In this step we create a function that can display the testimonials with the correct markup. Take a look at the code first, and don’t be afraid, it might be a bit more complex than the previous code snippets but I will explain it all for you.

	// Displaying the testimonials
	function display_testimonial_slider() {

		// We only want posts of the testimonials type
		$args = array(
			'post_type' => 'testimonials',
			'posts_per_page' => 5
		);

		// We create our html in the result variable
		$result .='<div id="slides testimonials"><div class="slides_container">';

		$the_query = new WP_Query($args);

		// Creating a new side loop
		while ( $the_query->have_posts() ) : $the_query->the_post();

			$client_name_value =get_post_meta(get_the_ID(), 'Client Name', true);
			$link_value = get_post_meta(get_the_ID(), 'Link', true);

			$result .='<div class="slide">';

			// Displaying the content
			$result .= '<div class="testimonial">'.get_the_content().'</div>';

			// Displaying the author of the testimonial and also creating a link if the Link custom field is provided
			if ($link_value != '') {
				$result .= '<div class="testimonial-author"><a href="http://'.$link_value.'" >'.$client_name_value.'</a></div>';
			}
			else {
				$result .= '<div class="testimonial-author">'.$client_name_value.'</div>';
			}

			$result .='</div>';

		endwhile;

		$result .= '</div></div>';

		return $result;
	}

Let’s see the code step by step! First we are setting the parameters of our side loop. We are only interested in ‘testimonials‘ type posts and we only want five of them. Then we are creating the $results variable. We will store our HTML markup in it. If you check the SlideJS docs or examples you can see that we need some specific mark-up for the plugin to work. We are creating it and concatenating everything to the $results variable. In the loop we get the content of our testimonial and also get the values of the Client name and Link custom fields (if we have a link the Client name will be clickable). We also use some extra markup so it will be easy if you want to style them.


Step 6 Creating the Shortcode

Our slider is not fully functional yet, as it isn’t sliding our posts, but it would be good if we could see if it displays our testimonials correctly at least. So let’s add a shortcode so we can see what we are displaying!

	// Adding shortcode
	add_shortcode('client testimonials', 'display_testimonial_slider');

As you can see, adding shortcode support is really easy. Now if write [client testimonials] in our page or posts we can see the client testimonials, as you can see in the image (I added some testimonials, so we have something to display).


Step 7 Making the Testimonials Slide

Now that we are sure that our testimonials are displaying correctly let’s make them slide! Do you remember the script.js file that we added to the head of our page? Now we will create it! So, if you have not already done that, create an empty file called script.js in the js folder in the plugin directory and add the following code:

	jQuery(function() {
		jQuery("#slides").slides({
			generatePagination: false,
			play: 3000
		});
	});

I didn’t want pagination for the sliders and put it to autoplay, so it’s discretely sliding at the top or where you want it to. If you want to use extra features of SlideJS you can easily do that from reading its documentation.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • http://prop-14.com Randy

    Very nice tut. Ok, this is extremely “nit-picky” but I prefer singular post type names like “testimonial”. This follows the WordPress naming convention better such as with “post” or “page”, both singular.

    Also, I am fairly certain that having a space in your short code name is not allowed? It should be an underscore maybe. Seems to me it would treat the word “testimonials” as an argument. Not that it will affect anything.

    • http://cloudofthemes.com Connor Crosby

      I am pretty sure you cannot have spaces either for shortcodes. But anyways, good tutorial :)

  • Pingback: Building a Client Testimonials Slider Plugin | Qtiva

  • http://lukespoor.com Luke S

    This is brill, but how would I go about giving each post/testimonial in the post type a custom ID so different ones could be accessed with a shortcode of [testimonial id="#"] for example.

  • http://www.studiowizjo.pl Bartłomiej

    There is a small typo in the shortcode listing: dispaly_testimonial_slider instead of display_testimonial_slider. Besides, really great tut. Appreciate that!

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

      Oops! Thanks for pointing that out :) Corrected now.

  • Ravi Shekhar

    Typo

    $result .=”;

    should be

    $result .=”;

  • Ravi Shekhar

    Typo

    Line #11 in Step 5 , the id and class definition has error. that’s why, the slider is not running on my local…

    Awesome effort.

    • Kevin

      What is error that you note?

      I can get the posts to show, cannnot get them to slide.

      Step 7, where are you adding this code?

      • Franco Musso

        The line should read:
        $result =’<div id=”slides”><div class=”testimonials slides_container”>’;

        rather than:
        $result .=’<div id=”slides testimonials”><div class=”slides_container”>’;

        Without that, the script.js file is looking for divs with an id that doesn’t exist.

        In step 7, the code goes in a new file called script.js within the plugins>js folder
        I hope that helps!
        Franco

        • Chris Raymond

          An element can have only a single ID, but multiple classes. So is invalid.

  • http://www.bagaimana.biz Hadie Danker

    really great tutorial. Appreciate that! thank you.

  • http://www.vanhove.com Steve VanHove

    This is a great idea and tutorial, but I’m not sure it’s a good replacement for the sliding photos. After all, that is a very visible part of a website.From a marketing perspective, it might be a better idea to use a slider in that area that has your Irresistible Offer and/or your Unique Selling Proposition. That’s what I did on my site – and with photos. Please take a look and let me know what you think. :)

  • http://leoneldelacruz.com Leonel De La Cruz

    For those that would like to use the shortcode within a text widget, add the following to your code in step 6:

    add_filter(‘widget_text’, ‘do_shortcode’);

  • Pingback: My First WordPress Plugin – Testimonial Slider - Powerkords | Powerkords

  • Albert

    On step three line 1 while in debug mode PHP notices get generated because the post type isn’t being set, this is how i’ve fixed it:

    if ((isset($_GET['post_type']) && $_GET['post_type'] == ‘testimonials’) || (isset($post_type) && $post_type == ‘testimonials’)) {

  • http://www.mctipit.com McTip IT

    Excellent I have been looking to develop a testimonial plugin for my website. This should be spot on, nice tutorial.

  • Permanence

    Great tut, works well. One question, how can we create an archive page to display all testimonials?

  • Pingback: 16 Helpful Tutorials for Creating WordPress Plugins

  • zzap

    A little extra touch on this. I always like to add custom columns to manage custom post type page (edit.php?post_type=POST_TYPE). It looks empty with default ones and every custom post type has specific features which can be highlighted in these columns.

    This piece of code can be added at the end of testimonialplugin.php file:

    // Add new columns
    function testimonials_columns_head($defaults) {
    $defaults['client_name'] = __(‘Client Name’, ‘textdomain’);
    $defaults['client_link'] = __(‘Client Link’, ‘textdomain’);
    return $defaults;
    }
    // Get and display custom fields values
    function testimonials_columns_content($column_name, $post_ID) {

    global $post;
    $name = get_post_meta($post->ID, ‘Client Name’, true);
    $url = get_post_meta($post->ID, ‘Client Link’, true);

    if ($column_name == ‘client_name’) {
    echo $name;
    }
    if ($column_name == ‘client_link’) {
    echo $url;
    }
    }
    // Make these columns sortable
    function testimonials_sortable_columns() {
    return array(
    ‘client_name’ => ‘client_name’,
    ‘client_link’ => ‘client_link’
    );
    }
    add_filter(‘manage_testimonials_posts_columns’, ‘testimonials_columns_head’);
    add_filter(‘manage_testimonials_posts_custom_column’, ‘testimonials_columns_content’, 10, 2);
    add_filter(‘manage_edit-testimonials_sortable_columns’, ‘testimonials_sortable_columns’);

  • http://www.peterogara.info Peter

    Great Tutorial, thanks
    I have added categories to the testimonial custom post type and was wondering how I would go about displaying these using a shortcode.

  • Silvia Gil

    Hi! Great plugin thank you! Works perfectly in Chrome, but in Firefox lines are not complete.
    http://madrid-casas.es/noticias/

    Let me know if this can be arranged.
    Thanks a lot!

  • Pingback: Tutorials Που Θα Σας Βοηθήσουν Να Δημιουργήσετε Το Πρώτο Σας WP Plugin | Ελληνική Κοινότητα WordPress

  • http://www.prizebond.biz/ Reihaan

    Great tutorial working on my website to create one, it seems good, now going to use it..Will update when i am finished with it…

  • Redd

    Hi!

    I downloaded the plugin and installed on my website but it doesn’t works well the testimonial posts cant be found. Does anyone can give a working code?

    Thanks a lot!

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

  • Spacechimp

    Hi Richard, Great tutorial thanks! this is the first plugin I’ve made and I’ve learned a lot.

    I made a minor change to the plugin by adding ‘taxonomies’ => array(‘category’), to line 14. With this i can use wordpress categories and display specific testimonials on relevant pages using the following code:

    'testimonials', 'posts_per_page' => 10, 'cat' => 4,);
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();

    echo '';

    echo '';
    echo '';
    the_title();
    echo '
    ';

    echo ' ';
    the_post_thumbnail();
    echo ' ';

    echo '

    ';
    the_content('MORE >');
    echo '

    ';

    echo ' ';
    endwhile; ?>

    My question is, how can i display the custom fields we created in step3?

    Many thanks

  • Spacechimp

    the code won’t display as intended so i made a screenshot to make things clearer

  • Danny

    Hi! Great plugin thank you! Works perfectly in Chrome, but in Firefox and ie some lines are missing.

    would you please let me know whats the problem.

    Thanks

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