I assume that you are a freelance designer or someone who work full time as a designer for a web design agency. Most of web designers are used work with static website design.

Now the question is: do you have a future as a static website designer?

The answer would probably be no since most clients and companies are planning to convert their websites to work with a CMS like WordPress, Joomla or Drupal.

WordPress is becoming the new static web site.

WordPress integration is simple enough that almost anyone can setup a WordPress site with an auto installer program. Unless you are familiar in working with a CMS like WordPress, you will definitely face issues moving further as a freelance designer. And you will seriously speed up your website development process, read exactly how in this article.

Table of Contents:

  1. WordPress Plugin Development Course for Designers – What to Expect
  2. Understanding WordPress Plugin Structure
  3. Basics for Creating WordPress Plugin Template
  4. Integrating Your Favorite Slider into WordPress
  5. Enhancing WordPress Plugins with Add On Features

Download the Source Files.

What to Expect from this Course

Being a designer, your main focus should be to learn WordPress theme design and development. But clients are never going to be satisfied, even if you build their websites with professional theme and design. They will ask you for more and more features as they know that it’s easier to build things with WordPress.

WordPress plugins are a quick and easy solution to wrap your site with additional functionality such as social integration, breadcrumbs, Google Maps, etc. If you are not familiar with using and customizing plugins, you will need the support of a developer to keep clients from going from you and go looking for another developer who is capable of providing both design and development tasks.

Hiring a developer and creating the custom functionality can be costly for you as a freelance designer. So you should be thinking about learning the skills of plugin development.

What Can You Expect From Us?

The initial part of this tutorial series will consist of four parts, where we will learn WP Plugin Development from scratch. Throughout the series we will be developing a WordPress plugin to integrate your favorite jQuery Slider. Final output will be a complete slider plugin for WordPress, which you use in any part of the CMS.

Understanding WordPress Plugin Structure

WordPress plugins lets us create additional functionality without affecting the core system. As designers, our main focus should be to develop quality front-end plugins with awesome designs rather than developing highly technical back-end plugins to provide complex functionality.

So it’s important to know the basic structure,initial components and functions of a plugin to get things started.

What are the prerequisites?

Throughout this series you will have to work with technologies like PHP, JavaScript, and MySql. It’s ideal to have basic knowledge of those technologies, although it’s not mandatory. As designers, I don’t expect you to have knowledge on working with server side technologies and databases. But basics of JavaScript will be handy and I assume you have the basic idea.

Should You Create Plugins from Scratch?

I think the answer should be no, in situations where you can find a free plugin to implement the required features. WordPress plugin repository is full of plugins with wide range of capabilities. It’s much easier to find a plugin from the repository rather than creating from scratch.

Even though the repository contains around 20,000 plugins, there is no guarantee that there will be plugins to suit each and every requirement in your projects. In such cases you will have to either modify an existing plugin or write your own plugin from scratch.

Components of WordPress Plugin

We will be focusing on creating web design related plugins throughout this series. So these plugins will have some kind output to the browser using combination of HTML, CSS and JavaScript. This will be considered as the front-end component of the plugin.

Usually we need to change the design components with dynamic data. Therefore we have to create a custom section inside WordPress Admin panel to enter dynamic data and options. This data creation section can be considered as the back-end component of the plugin.

Let’s take a look at the back-end and front-end of a premium slider plugin from Themeforest.

Frond-end of the Plugin

wpbs_08

Back-end of the Plugin

wpbs_09

You can see how these components are used effectively in professional plugins. Simplest plugins will not require a back-end component. Here we will be creating a slider with both front-end and back-end components.

Creating Your First Plugin

First we have to know where to create plugins inside the WordPress installation. WordPress consists of 3 main folders called wp-content, wp-admin and wp-includes.

The following screenshots previews the files and folders available inside WordPress installation. Our focus will be on the highlighted wp-content folder, where we install our themes and plugins.

wpbs_04

Inside wp-content, you will find another folder called plugins. Now switch to plugins folder and you will see few default plugin folders created by the WordPress installation. This will be the place where we create our own plugins.

Following screen shows the list of folders available inside wp-content folder.

wpbs_03

We can directly create a plugin inside the plugins folder by including the plugin file. But the recommended method is to create each plugin in a separate folder inside the plugins folder.

So let’s name our plugin as 1WD Slider and create a folder called 1wd-slider. It’s important to know that there is no restriction on naming the plugin folder. I prefer using the plugin name as the folder name for keeping consistency. The following image shows our plugin folder inside the plugins.

wpbs_02

Creating Plugin File

Plugins can contain any number of files as you want. For the purpose of this tutorial, I am going to create the plugin as a single PHP file. So create a file called 1wd_slider.php inside your plugin folder.

Once again there are no restrictions in naming plugin files. Having created plugin folder and file, let’s see how it displays on WordPress plugins list.

Login to your WordPress account as admin and click on Plugins tab on the left to get a list of available plugins.

wpbs_05

Surprisingly, the plugin list does not show our plugin. What is the reason?

Even though we created both plugin folder and file, we did not inform WordPress to consider it as a plugin. We have to add a PHP comment in predefined format on top of the file to make it a WordPress plugin. Open the 1wd_slider.php file and insert the following PHP comment.

<?php /* Plugin Name: 1WD Slider Plugin URI: https://1stwebdesigner.com/ Description: Slider Component for WordPress Version: 1.0 Author: Rakhitha Nimesh Author URI: https://1stwebdesigner.com/ License: GPLv2 or later */ ?>

As a designer you might not be familiar with PHP codes, hence I’ll explain the code in detail. Tags <?php and ?> is used respectively for opening and closing PHP codes. This is similar to script tags in JavaScript. Anything you place between these tags will be executed as PHP codes.

Then we have a multiple line comment which is similar to comment syntax in JavaScript. We can use /* */ for multiple line comments and // for single line comments.

Inside the comment we have defined plugin details in key value structure. Basically Plugin Name will be the most important and mandatory parameter. Once you set the Plugin Name, WordPress will identify your file as a plugin to display in the plugin list. Following screen contains our plugin with complete details.

wpbs_06

Now let’s go through the remainder of parameters by comparing with the screen.

  • Plugin URI – is used to let users know about the details of the plugin and available download options. This isn’t mandatory and you can keep it blank, if you don’t have an intention of making the plugin publicly available.
  • Description – is used to provide a summary of functionality of the plugin.
  • Version – is used to define the version and you can use any numbering format as you wish. Plugins need be upgraded with each WordPress version upgrade. Therefore it’s good to have proper version numbering even though it’s not mandatory.
  • Author and Author URI – is used to provide details about the developer of the plugin.
  • License – is used to define the conditions for using this plugin. We can include standard licence such as GPL2 or just mention something we prefer such as Free to use.

We don’t need to consider about the parameters other than plugin name, in case we are not making the plugin publicly available for use.

Now we have our first WordPress plugin, even though it doesn’t do anything at the moment. We can activate or deactivate plugins from the plugin list.

Let’s discuss more on plugin activation.

WordPress Plugin Activation and Deactivation

Plugins will be on inactive status by default. We can click on the activate link under the plugin name to activate the plugin. Once the plugin is successfully activated, its features will get effected to your website.

Also you should be able to see deactivate link instead of activate link after a successful activation. Clicking the deactivate link will revert the status of the plugin to its original inactive status.

wpbs_07

What Can We Do on Activation/Deactivation?

Think about a real world scenario where you activate premium membership of a club or library. Obviously you will get added benefits on activation and you will lose those benefits on deactivation. Similarly we can execute some tasks on plugin activation and deactivation.

WordPress provides a concept called hooks, where you can trigger certain tasks to add new behavior or modify existing behavior. So let’s look into the code for activation and deactivation hooks.

function fwds_slider_activation() {
}
register_activation_hook(__FILE__, 'fwds_slider_activation');
function fwds_slider_deactivation() {
}
register_deactivation_hook(__FILE__, 'fwds_slider_deactivation');

Above code contains two functions called fwds_slider_activation and fwds_slider_deactivation. PHP function is a reusable piece of code where we can execute multiple times. Even as a designer you might have a basic idea about functions since PHP functions are similar to JavaScript functions.

Then we have the two hooks called register_activation_hook and register_deactivation_hook. Don’t worry too much about hooks as you will understand them while learning about plugin development in this series.

For the moment just define these hooks with plugin specific activation and deactivation functions and execute necessary codes inside the function.

Why Do We Use Activation/Deactivation Hooks

We can create basic plugins without considering activation and deactivation functions. But advanced plugin will require these functions to provide additional features.

Following is a list of possible things we can do inside plugin activation/deactivation.

  • Create custom database tables on activation to store data and remove tables on deactivation.
  • Create custom options for plugins and activation and reset in deactivation.
  • Validate other dependent plugin on activation.
  • Any other necessary task you need to execute in activation.

Now we have discussed the importance of WordPress plugins for designers and its structure. From next part onwards we will be digging into the technical aspects of WordPress plugins.

Don’t be afraid of complex PHP or JavaScript codes since I will be covering all the necessary details about those codes in a simplified manner to suit web designers.

Coming Up

In the next part we will be digging into the actual code to learn the necessary functionality for creating a plugin. WordPress core functions needed to implement plugins will be discussed in detail from designers perspective.

Throughout the next part we will be building a template for creating design based plugins. Until then I suggest that you read the following resources and get an ideas about plugin development.

You can grab a copy of the plugin here. The plugin does not include any functionality yet. So you can only see how it activates and deactivates using WordPress admin.

I have made my explanations in a simplified manner to suit web designers. Still I know that it can be difficult for designers who basically concentrate on HTML, CSS without considering JavaScript.

So let me know anything you didn’t understand through the comment section and I’ll get back to you with much more simplified explanations. Also let me know what is your preferred slider and why you voted for it.

Let’s take the next step.

Basics for Creating WordPress Plugin Template

Today we are going to talk about the core WordPress theories and techniques required for creating design focused plugins. Our final goal is to learn WP plugin development while integrating a jQuery slider into WordPress from scratch.

Throughout this tutorial, we will be learning the necessary coding techniques using sample slider as the example. By the end of this tutorial, you will have a simple template which is common to most of the design based plugins.

Download Source Files.

What type of files are needed for Design Based Plugins?

Consider the following image which illustrates the files in a common plugin for creating design based components.

wp1stw2d copy

As you can see JavaScript and CSS will be kept in separate folders inside the main plugin. The main PHP file contains the plugin definition and the important initialization functions of the plugin. If you are developing a single file plugin, all the codes will be kept inside the main PHP file.

Although HTML is the most important type of file for you as designers, it doesn’t show up as separate files in the given screen. Actually there won’t be any HTML files inside the WordPress plugin. All the necessary HTML codes are generated through PHP files.

The preceding screen shows the basic folder and file structure of a WordPress plugin. We can add necessary libraries and additional files to modularize our plugin to increase the reusability.

Understanding the Components of the Slider

Throughout this series we will be integrating a jQuery slider plugin to learn WP plugin development. Therefore it’s important to get used to the main components of a jQuery slider as shown in the following.

  • jQuery library – We need a core library to develop plugins. jQuery is chosen as the core library for the plugin used in this series. You have the freedom to work with other core libraries such as Prototype, Dojo, MooTools, etc.
  • jQuery plugin file – Every plugin has a main file which is built on top of the jQuery library. Usually we have all the codes for a jQuery plugin inside single JavaScript file.
  • Intialization code – All the plugins need to be initialized at some point to make it work. Generally we use inline scripts in the HEAD section of the HTML document to include the initialization code.
  • CSS files used for plugin – Most of the content or image sliders uses CSS to provide slide transitions and animations. Therefore we have CSS files specific to plugins to provide the default look and feel of the sliders.
  • HTML or Images used for sliding – Final component of a slider is the actual text, image or HTML content which gets converted into a slider by the plugin. Unordered list with HTML and images is the most popular technique of defining the data required for the slider.

Now we have identified the main five components of a jQuery slider plugin. Let’s focus on learning how each of these components fit into an actual WordPress plugin.

Including Scripts in WordPress Plugins

Our slider plugin contains two JavaScript files at the moment and will have the third one for plugin initialization code. Most of the beginner developers makes the mistake of including scripts incorrectly inside WordPress plugins.

So this section will focus on identifying the mistakes and learning how to avoid those mistakes in order to comply with the best practices.

I assume that most of the readers of this tutorial will be designers. So let’s see how we include script files in static HTML websites.

<html>
<head>
  <script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>
  <script type='text/javascript' src='jquery.slides.min.js'></script>
  <script type='text/javascript'>
        jQuery(function() {
           jQuery('#slides').slidesjs({
              width: 940,
              height: 528,
              navigation: false
            });
        });
  </script>
</head>
<body>

</body>
</html>

We basically hard code all the script files into HEAD section of the HTML document or footer section. This is not a problem at this stage since we are building static websites. Now let’s see how these scripts are included in WordPress plugin by developers who are not experienced in WordPress.

The Wrong Way of Including Scripts

Most inexperienced developers directly includes the scripts inside the PHP files using the echo statement as shown in the following code. This is considered as a bad practice in plugin development.

function fwds_scripts(){

 echo "<script type='text/javascript' src='http://code.jquery.com/jquery-latest.min.js'></script>";

 echo "<script type='text/javascript' src='jquery.slides.min.js'></script>";
}

The code prints the script files anywhere in the HTML file. It can be header, footer or body depending on location you place it. Even though we have a separate header for WordPress themes, it’s not wise to hard code the files in the header.

In static websites you can manage these files since you will be the only designer. WordPress has a plugin based architecture and hence anyone can write plugins. Therefore there is a high possibility of duplicating the same files with the technique mentioned above.

The Right Way of Including Scripts

Now we are going to look at the right way of including scripts, considering the limitations in above technique. WordPress came up with a concept called action hooks which will be executed at specific points of a request or when a specific event occurs in your system. You can define a functions to be called in these execution points.

It will take time to understand the complete concept of WordPress action hooks, even for an experienced WordPress developer. For the moment think of it as a code that calls PHP function at specific points. Consider the following code.

< ?php
function my_custom_function() {
  // Place the code to be executed here
}

add_action('action name', 'my_custom_function');
?>

We can replace the action name with predefined WordPress hooks or using our own custom hooks. You have to use different functions to different actions. In depth knowledge of action hooks will be provided in future tutorials when you get comfortable with basics of plugin development.

Now let’s switch back to the correct method for including scripts. WordPress provides a predefined hook called wp_enqueue_scripts to include script files into pages. Inside our custom function we have to include the scripts one by one. Consider the following code.

<?php

add_action('wp_enqueue_scripts', 'fwds_scripts');
function fwds_scripts() {

wp_enqueue_script('jquery');

wp_register_script('slidesjs_core', plugins_url('js/jquery.slides.min.js', __FILE__),array("jquery"));
wp_enqueue_script('slidesjs_core');

wp_register_script('slidesjs_init', plugins_url('js/slidesjs.initialize.js', __FILE__));
wp_enqueue_script('slidesjs_init');

}
?>

Preceding code calls the fwds_scripts function in the execution process using the wp_enqueue_scripts action. I have used fwds(first web designer slider) as the prefix for my functions.

It is recommended to prefix your plugin functions with string related to your plugin name to avoid conflicts with functions in other plugins.

Inside fwds_scripts, we have used two other functions for including script files called wp_enqueue_script and wp_register_script. wp_enqueue_script is used to include the script file to the HTML document.

jQuery is one of the libraries which comes in-built with WordPress and hence we can include it directly as shown in the code. Latest version of jQuery will be included in this technique.

wp_register_script is used to register a script file into WordPress. We have to register the slider plugin file and initialization file since it is not built-in with WordPress. First parameter is a unique name to register your library.

Next you have to provide the path of the js file. plugins_url function will provide the URL of the plugin folder.

Third parameter specifies the dependent libraries. In this scenario, our plugin file depends on the jQuery library. We don’t have to manage dependencies with this technique. Before registering any script, WordPress checks whether it has been already registered using the given unique name. File is loaded only when it’s not loaded previously. So it will prevent the file duplication discussed in the earlier section.

If you register the same script file with different names, WordPress will not be able to handle the file duplication.

SlidesJs core plugin file is named as jquery.slides.min.js and we have included it in the preceding code. Also we have included the initialization part of the library inside another js file called slidesjs.initialize.js. Following code contains the initialization code inside the js file.

jQuery(function() {
    jQuery('#slides').slidesjs({
      width: 940,
      height: 528,
      navigation: false
    });
});

There are various other recommended ways of including scripts files without using wp_enqueue_scripts action hook. Technique discussed here is good enough for us to learn plugin development as designers. I will also cover the other techniques when required.

Including Styles in WordPress Plugins

Usually most of the jQuery plugins comes up with built-in CSS file to provide its default look and feel. As designers we are used to including CSS files directly in the HTML document. So the beginners of WP plugin development tries to apply the same method as I discussed in JavaScript section.

The Wrong Way of Including Styles

Consider the following code to see how beginners include CSS files in WordPress plugins.

function fwds_styles(){
  echo <link rel='stylesheet' href='example.css' type='text/css' media='all' />";
  echo <link rel='stylesheet' href='font-awesome.min.css' type='text/css' media='all' />";
}

The code will include style files everywhere in the HTML document without considering file duplication. This works exactly the same way how JavaScript worked.

The Right Way of Including Styles

Recommended method of including style files is exactly similar to the method we discussed for JavaScript files. wp_enqueue_scripts action will be used again with different function name to include the styles as shown in the following code.

add_action('wp_enqueue_scripts', 'fwds_styles');
function fwds_styles() {

wp_register_style('slidesjs_example', plugins_url('css/example.css', __FILE__));
wp_enqueue_style('slidesjs_example');
wp_register_style('slidesjs_fonts', plugins_url('css/font-awesome.min.css', __FILE__));
wp_enqueue_style('slidesjs_fonts');

}

We have to use wp_register_style and wp_enqueue_style in this case instead of script functions. Usage and parameters are exactly similar to script functions.

In this part, we are using SlidesJS for implementing the slider plugin. SlidesJS comes up with two CSS files for styles neccessary for look and feel of the presentation and including fonts.

Now we know the basics of including scripts and styles of the jQuery plugin inside the WordPress plugin. Generally we place the initialization code for a plugin, inline within script tags in static HTML files. With WordPress, it’s better to add it to an existing js file or include in a new js file and load using the recommended way.

Assigning Content to Slider Using Shortcodes

Shortcodes can be considered as an alias for reusable piece of code. First we have to define the common code inside a PHP function. Then we can access it anywhere in themes, plugins or page editor by using the alias given for function. Consider the code below for most basic use of WordPress shortcode.

add_shortcode("my_shortcode", "my_shortcode_function");

function my_shortcode_function() {
return "<h1>Hello Shortcodes</h1>";
}

WordPress provides a built-in method called add_shortcode for defining shortcodes. First parameter is the name (alias) of the shortcode. Second parameter contains the function to be executed when the shortcode is requested. We return a simple string from the shortcode.

Some developers like to directly print the output of the shortcode inside the function. You should always prefer returning output from function and printing externally as shown in the preceding example.

Then you can use [my_shortcode/] to refer the common code in multiple locations. Folowing screen shows how you can use a shortcode inside the post or page editor in WordPress.

shortcodes_editr

Shortcodes can be used inside theme or plugin files with do_shortcode function as shown below.

<?php echo do_shortcode('[my_shortcode]') ?>

Advanced Usage of Shortcodes

In the previous example, we used the most basic form of shortcode. We can also have attributes and content in shortcodes to add additional features. Consider the following shortcode with attributes and content.

[my_advanced_shortcode name="Nimesh" age="27"] Description about me [/my_advanced_shortcode]

These types of shortcodes contain opening and closing shortcode tags. Information placed between the opening and closing tags is considered content and key-value pairs inside the opening tag is considered as attributes. Following code shows how we can extract these information inside the actual shortcode function.

function my_advanced_shortcode_handler( $atts, $content = null ) {
 extract( shortcode_atts( array(
    'name' => 'Rakhitha',
    'age' => '20'
    ), $atts ) );

 echo $name;
 echo $age;
 echo $content;
}

Content and attributes of the shortcodes will passed as the default parameters to shortcode function. We can directly use the content using the $content variable. Here you will get “Description about me” as the content.

Handling attributes is not straightforward as content. We have to extract each attribute from the $attr array. We can use the extract function as shown here. We define all the attribute with the default values.

If attributes are supplied with shortcodes, default value will be replaced by passes value. Finally you can access these attributes using $name and $age.

Integrating Slider Using Shortcodes

In the previous sections we discussed how scripts, styles and initialization code fits into a WordPress plugin. Final part of the slider will be the actual HTML or images used as the content for sliding. Shortcodes will be the ideal method for providing slider content. Now let’s see how images fit into the shortcode.

add_shortcode("1wd_slider", "fwds_display_slider");
function fwds_display_slider() {

$plugins_url = plugins_url();

echo '<div class="container">
  <div id="slides">
    <img src="'.plugins_url( 'img/example-slide-1.jpg' , __FILE__ ).'" />
    <img src="'.plugins_url( 'img/example-slide-2.jpg' , __FILE__ ).'" />
    <img src="'.plugins_url( 'img/example-slide-3.jpg' , __FILE__ ).'" />
    <img src="'.plugins_url( 'img/example-slide-4.jpg' , __FILE__ ).'" />
    <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left icon-large"></i></a>
    <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right icon-large"></i></a>
  </div>
</div>';
}

Now we have integrated all the necessary parts into WordPress plugin. But we still have a slider with static content. Real power of plugin comes when we can add the slider content dynamically and create multiple sliders to use in multiple locations.

Now you can download the static version of WordPress slider plugin here.

Copy the downloaded plugin into plugins folder and activate using the admin dashboard. Then create a post or page and insert [1wd_slider/] in the TinyMCE editor and click the publish button to see the slider in action. You will be able to use the navigation button to see how sliding works.

So try out the static version of slider plugin for multiple jQuery libraries using the following template we created throughout this tutorial.

<?php

/*
Plugin Name: 1WD Slider
Plugin URI:  />Description: Slider Component for WordPress
Version: 1.0
Author: Rakhitha Nimesh
Author URI:  />License: GPLv2 or later
*/
function fwds_slider_activation() {
}
register_activation_hook(__FILE__, 'fwds_slider_activation');

function fwds_slider_deactivation() {
}
register_deactivation_hook(__FILE__, 'fwds_slider_deactivation');

add_action('wp_enqueue_scripts', 'fwds_scripts');
function fwds_scripts() {

wp_enqueue_script('jquery');

wp_register_script('slidesjs_core', plugins_url('js/jquery.slides.min.js', __FILE__),array("jquery"));
wp_enqueue_script('slidesjs_core');

wp_register_script('slidesjs_init', plugins_url('js/slidesjs.initialize.js', __FILE__));
wp_enqueue_script('slidesjs_init');

}

add_action('wp_enqueue_scripts', 'fwds_styles');
function fwds_styles() {

wp_register_style('slidesjs_example', plugins_url('css/example.css', __FILE__));
wp_enqueue_style('slidesjs_example');
wp_register_style('slidesjs_fonts', plugins_url('css/font-awesome.min.css', __FILE__));
wp_enqueue_style('slidesjs_fonts');

}

add_shortcode("1wd_slider", "fwds_display_slider");
function fwds_display_slider() {

$plugins_url = plugins_url();

echo '<div class="container">
  <div id="slides">
    <img src="'.plugins_url( 'img/example-slide-1.jpg' , __FILE__ ).'" />
    <img src="'.plugins_url( 'img/example-slide-2.jpg' , __FILE__ ).'" />
    <img src="'.plugins_url( 'img/example-slide-3.jpg' , __FILE__ ).'" />
    <img src="'.plugins_url( 'img/example-slide-4.jpg' , __FILE__ ).'" />
    <a href="#" class="slidesjs-previous slidesjs-navigation"><i class="icon-chevron-left icon-large"></i></a>
    <a href="#" class="slidesjs-next slidesjs-navigation"><i class="icon-chevron-right icon-large"></i></a>
  </div>
</div>';
}
?>

Demo and Challenge

1wd-wordpress-plugin-development-course

Now, here’s a challenge to you:

If you have installed the plugin and checked, you will notice that it occupies a full width of 940px. And on our demo site the slider has overlapped the sidebar because of this. Question is, can you make it responsive on your own? It’s easy!

Up Next

In the next part we will be creating the actual integration of jQuery plugin into WordPress. Instead of just hard coding HTML or images inside unordered lists, we will be creating sections to upload images dynamically and create multiple sliders by selecting preferred images.

Until then I would like to suggest following resources to get an idea about the contents in the next part of this tutorial series.

Now it’s your turn.

Integrate various other sliders using the technique we discussed today. Now don’t worry about sliders being static at the moment. I will explain how to make it dynamic and reusable in the next part.

Let me know about the type of sliders you tried and any difficulties you faced in applying the discussed technique.

We are on a good path to success, the next part is about integrating the plugin to WordPress.

Integrating Your Favorite Slider into WordPress

In the first part we identified the importance of WordPress plugins for you as designers and the basic structure of a plugin. Then we followed it up with the necessary coding required for developing plugins by creating a jQuery slider for WordPress. Now we are going to integrate it to WordPress.

I hope you have used the slider plugin and tried to fix the responsive issue we had in the demo. We got good responses containing the possible solutions. So we are going to start the third part by fixing the responsive issue in the slider.

Following is an image from demo we created in the previous part, illustrating the responsive issue.

wpdd_part3_1

Making SlidesJS Responsive

SlidesJS is designed to use 940px as its default width. Most of the websites are designed in a grid with at least 960px width. So default SlidesJS slider will be responsive in full width pages. We are using the TwentyEleven theme in this demo.

It doesn’t offer the full width in its default pages or posts. Therefore we have to adjust the slider according to our themes to make it responsive.

CSS media queries can be used effectively to make the slider responsive. So let’s take a look at the default media queries provided by SlidesJS.

<style>
<!--
/* For tablets & smart phones */
   @media (max-width: 767px) {
     body {
       padding-left: 20px;
       padding-right: 20px;
     }
     .container {
       width: auto
     }
   }

   /* For smartphones */
   @media (max-width: 480px) {
     .container {
       width: auto
     }
   }

   /* For smaller displays like laptops */
   @media (min-width: 768px) and (max-width: 979px) {
     .container {
       width: 724px
     }
   }

   /* For larger displays */
   @media (min-width: 1200px) {
     .container {
       width: 1170px
     }
   }

-->
</style>

960px layouts will fit into the media query between 768px and 979px. Slider container is defined as 724px for that particular width range. Basically what you have to do is adjusting the width of slider container based on your themes content area dimensions. So the updated media queries to suit TwentyEleven theme are as follows.

<style>
<!--
    /* For tablets & smart phones */
    @media (max-width: 767px) {
      body {
        padding-left: 20px;
        padding-right: 20px;
      }
      .container {
        width: 400px
      }
    }

    /* For smartphones */
    @media (max-width: 480px) {
      .container {
        width: 300px;
      }
    }

    /* For smaller displays like laptops */
    @media (min-width: 768px) and (max-width: 1199px) {
      .container {
        width: 600px
      }
    }

    /* For larger displays */
    @media (min-width: 1200px) {
      .container {
        width: 600px
      }
    }
-->
</style>

You can see that I have modified the widths of all the media queries to suit TwentyElevan theme container sizes. Now let’s look at the slider after the code updates. Make sure to add these styles for media queries into the example.css file in the plugin.

wpdd_part3_2

We have completed the responsive version of static slider for WordPress. But it’s useless until we enable the capabilities for adding images dynamically through the WordPress dashboard. So let’s get started on making dynamic sliders.

Planning the Dynamic Slider Functions

In the current version of the plugin, we are using the images inside the plugin folder. But we want to put our own images in an user friendly method. Also we should be able to create multiple sliders for different locations of our web sites. Let’s list down the functionality we need to implement in this part.

  • Create multiple sliders
  • Upload images dynamically through WordPress media uploader.
  • Assign and remove images of sliders at any given time

Implementing these functionalities is not a very difficult task for people who are knowledgeable in working with PHP. But as designers you might find it a little difficult to understand if you have zero background about PHP. So I am going to explain things as simple as possible to make it easy for you.

Also keep in mind that you don’t need to understand each and every detail discussed here. I’ll tell you the tasks you need to focus and tasks you can omit as designers. So stay tuned and get ready with your code editor.

Creating Slider – Role of Custom Post Type

Most of you will be familiar in working with WordPress posts. Even if you haven’t developed or designed anything on WordPress, there is a high possibility that you have wrote an article on a WordPress blog. WordPress posts are designed to write article, tutorials or some content for your website. Following image displays the post creation screen of WordPress.

wpdd_part3_3

Usually we get fields like post title, post content, categories, featured image to insert necessary data for specific posts. Similarly WordPress provides a technique called Custom Post Types. Basically custom post type can be considered as a special kind of post.

We can use custom post types to create some amazing designs and features to WordPress. In this part we are going to use specific custom post type to create sliders.

Most important thing to keep in mind is that custom post types doesn’t show in the normal post section and hence will not get displayed on your blog. We have the capability to create unique designs for these post types and decide where we should display them.

Creating Slider Post Type

I assume that you have already installed and activated the previous version of the plugin we developed in the last part. Here I’ll be adding and modifying the existing codes of the plugin.

First we have to register a new post type for sliders. You can insert the following code into the end of the 1wd_slider.php file of the plugin.

add_action('init', 'fwds_register_slider');

function fwds_register_slider() {

    $labels = array(

       'menu_name' => _x('Sliders', 'slidesjs_slider'),

    );

    $args = array(

       'labels' => $labels,

       'hierarchical' => true,

       'description' => 'Slideshows',

       'supports' => array('title', 'editor'),

       'public' => true,

       'show_ui' => true,

       'show_in_menu' => true,

       'show_in_nav_menus' => true,

       'publicly_queryable' => true,

       'exclude_from_search' => false,

       'has_archive' => true,

       'query_var' => true,

       'can_export' => true,

       'rewrite' => true,

       'capability_type' => 'post'

    );

    register_post_type('slidesjs_slider', $args);

}

WordPress executes an action called init in its initialization process of a user request. We can call any function on the init action. Here I have used a function called fwds_register_slider.

Inside the function we have to define some labels and parameters for custom post types. Labels will decide the text displayed on menu items and forms. There is a bunch of arguments to configure various features of a custom post type. Finally we register the custom post type using the register_post_type function.

First parameter to this function will be the name of the custom type. You can use any unique name for that. Next we pass the arguments as the second parameter.

Understanding the complete code and configurations is not necessary at this stage as a beginner in WordPress. Following is a preview of the custom post type section for Sliders once we include this code.

wpdd_part3_4

As you can see, there is a separate section for Slider posts on the left menu and the label is converted into the text we used in the labels variable.

Things to Focus on:

  • Whenever you want to create Sliders, Accordions, Tabs or similar design components, use the following block of code with a new function name for init action.
  • In the labels section, change the text you want to appear and the unique post type name according to your preference.
  • Keep the arguments variable as it is now and don’t worry about the various parameters used there for the moment.
  • Finally use the same unique name used in the labels array for the register_post_type function.

Each time you use this code with different function and unique post type, new section will be added to the left menu. Now try to use Sliders in the dashboard.

We can use this section to create sliders. But still it works as normal post type and won’t do anything different. Our next task is to add images into sliders. Let’s move forward.

Creating Slider Image Fields

We have to insert different images to each new slider. WordPress meta boxes can be used effectively to add additional fields to the slider creation screen. Consider the following code.

add_action('add_meta_boxes', 'fwds_slider_meta_box');

function fwds_slider_meta_box() {

    add_meta_box("fwds-slider-images", "Slider Images", 'fwds_view_slider_images_box', "slidesjs_slider", "normal");

}

function fwds_view_slider_images_box() {
    global $post;

    $gallery_images = get_post_meta($post->ID, "_fwds_gallery_images", true);
    // print_r($gallery_images);exit;
    $gallery_images = ($gallery_images != '') ? json_decode($gallery_images) : array();

    // Use nonce for verification
    $html =  '<input type="hidden" name="fwds_slider_box_nonce" value="'. wp_create_nonce(basename(__FILE__)). '" />';

    $html .= '
'; $html .= "
<table class="form-table">
<tbody>
<tr>
<th><label for="Upload Images">Image 1</label></th>
<td><input id="fwds_slider_upload" type="text" name="gallery_img[]" value="".$gallery_images[0]."" /></td>
</tr>
<tr>
<th><label for="Upload Images">Image 2</label></th>
<td><input id="fwds_slider_upload" type="text" name="gallery_img[]" value="".$gallery_images[1]."" /></td>
</tr>
<tr>
<th><label for="Upload Images">Image 3</label></th>
<td><input id="fwds_slider_upload" type="text" name="gallery_img[]" value="".$gallery_images[2]."" /></td>
</tr>
<tr>
<th><label for="Upload Images">Image 4</label></th>
<td><input id="fwds_slider_upload" type="text" name="gallery_img[]" value="".$gallery_images[3]."" /></td>
</tr>
<tr>
<th><label for="Upload Images">Image 5</label></th>
<td><input id="fwds_slider_upload" type="text" name="gallery_img[]" value="".$gallery_images[4]."" /></td>
</tr>
</tbody>
</table>
";

        echo $html;

}

First we have to call a new function on add_meta_boxes action to create a meta box for our sliders. Inside the function we define a new meta box using the add_meta_box function as shown in the following code.

function fwds_slider_meta_box() {

    add_meta_box("fwds-slider-images", "Slider Images", 'fwds_view_slider_images_box', "slidesjs_slider", "normal");

}

First parameter is a unique key for meta box followed by meta box title. Third parameter is a new function to execute the meta boxes. Fourth parameter is the unique post type we created earlier and you can leave the final parameter to its default value of normal.

Then we need to create the fwds_view_slider_images_box function to implement the meta box.Inside the function we get the available image values for the current slider from the database. We can save images of each slider into database with slider id and a key (_fwds_gallery_images).

In the initial loading, there wont be any existing images and hence the gallery images will be empty. Then we create the fields for the images using HTML codes. I have used 5 text boxes here to enter 5 images for each slider.

Now your slider creation screen should look like the following image.

wpdd_part3_5

Things to Focus on:

  • Create add_meta_box functions and load it with respective parameters. If you are creating 2 types of sliders, use 2 add_meta_box functions.
  • Create new function like fwds_view_slider_images_box for each of the sliders you want to use.
  • I have used 5 images per slider. Add or remove text boxes according to your preference to get more or less images per slider.

Uploading Images to Slider

Now we can start uploading images to the slider. Just click the Add Media button on the Slider creation screen to load the WordPress media uploader. Then upload images as you do for normal posts. You should get a screen like the following once an image is uploaded.

wpdd_part3_6

In the link to section on the right, you can select whether to use the image as an attachment or media file. Select media file to get the direct link to the uploaded image. Now copy the link and close the upload window.

Then insert the copied image url into the Image 1 field we created earlier. Continue this process for all the slides you want to appear in the slider.

Once all the links are filled, your slider creation screen will look like the following.

wpdd_part3_7

Saving Slider Images

We have uploaded and inserted the images into the slider. Now images need to be saved to the database. Even though image fields are in the slider creation screen, it won’t be saved automatically when the post is saved. We have to use a simple code to insert the data into the database as shown below.

add_action('save_post', 'fwds_save_slider_info');

function fwds_save_slider_info($post_id) {

    // verify nonce

    if (!wp_verify_nonce($_POST['fwds_slider_box_nonce'], basename(__FILE__))) {

       return $post_id;

    }

    // check autosave

    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {

       return $post_id;

    }

    // check permissions

    if ('slidesjs_slider' == $_POST['post_type'] && current_user_can('edit_post', $post_id)) {

       /* Save Slider Images */

       //echo "
";print_r($_POST['gallery_img']);exit;

       $gallery_images = (isset($_POST['gallery_img']) ? $_POST['gallery_img'] : '');

       $gallery_images = strip_tags(json_encode($gallery_images));

       update_post_meta($post_id, "_fwds_gallery_images", $gallery_images);

    } else {

       return $post_id;

    }

}

We call a custom function on save_post action to save the image details to the database. update_post_meta function is used to save these details into the _fwds_gallery_images key. I’ll show you the things you need to know in this section as it might be little complex for the beginners in design.

Things to Focus on:

  • When you are saving different types of posts like sliders, accordions,tabs, make sure to create new function on save_post action and use this block of code.
  • Inside the check permission section, use your own post type instead of slidesjs_slider.
  • Use your own unique key like _fwds_gallery_images to save the data into the database.

Now when the slider is published, all the images will be saved to the database. Then click on the Sliders section from the left menu and you will get a list shown in the following image.

wpdd_part3_8

You will be able to see a separate shortocde in front of each slider you create. You can use these to generate sliders once we complete the following section.

Generating Slider Using Uploaded Section

In the previous part we used a shortcode function to include images to the slider as shown in the following code.

add_shortcode("1wd_slider", "fwds_display_slider");
function fwds_display_slider() {

 $plugins_url = plugins_url();

 echo '
<div class="container">
<div id="slides"><img alt="" src="'.plugins_url( 'img/example-slide-1.jpg' , __FILE__ ).'" />
 <img alt="" src="'.plugins_url( 'img/example-slide-2.jpg' , __FILE__ ).'" />
 <img alt="" src="'.plugins_url( 'img/example-slide-3.jpg' , __FILE__ ).'" />
 <img alt="" src="'.plugins_url( 'img/example-slide-4.jpg' , __FILE__ ).'" />
</div>
</div>

';
}

As you can see all the images are hard coded in this version. Now we have the option of using dynamic sliders as well as dynamic images. So let’s move into implementing the shortcode.

add_shortcode("1wd_slider", "fwds_display_slider");

function fwds_display_slider($attr,$content) {

    extract(shortcode_atts(array(

               'id' => ''

                   ), $attr));

          $gallery_images = get_post_meta($id, "_fwds_gallery_images", true);

          $gallery_images = ($gallery_images != '') ? json_decode($gallery_images) : array();

          $plugins_url = plugins_url();

         $html = '
<div class="container">
<div id="slides">
';

 foreach ($gallery_images as $gal_img) {

 if($gal_img != ""){

 $html .= "<img alt="" src="".$gal_img."" />";

 }

 }

 $html .= '

</div>
</div>
';

     return $html;

}

Now we use the post ID passed to the shortcodes to retrieve the images dynamically. Then we assign each image to the slider using a foreach loop. Finally we return the resulted slider to be displayed inside our pages.

Things to Focus on:

  • You can use get_post_meta function with specific key to load any kind of details saved in the database.
  • We can pass any number of attributes to shortcode and you have to include them inside the extract function to retrieve the values.
  • Here we are getting image links from database. You can get and save any type of information using the get_post_meta function according to your shortcode type.

Now we have completed our slider plugin for this part and you can try creating sliders with different images. Once created, copy the shortwcode from the list and insert into a post or page to see it in action.

Following image shows the preview of our slider.

wpdd_part3_9

What’s Next?

In this part we completed the slider functionality. Now its dynamic and effective to suit various types of sections in your web pages.

What about sizes, effects, speeds of sliders?

Definitely a plugin becomes much more user friendly and customizable when you have options to choose and settings to define it’s features. So in the next part we will be adding options to our slider to complete the initial part of this plugin development series.

By the end of next part you will be able to create basic WordPress plugins for UI components using the techniques discussed here. Until then I hope you will practice these theories with different sliders.

Can You Solve These?

In the previous part I asked you to fix the responsive issues in the slider. In this part I provided more questions to solve and learn. Try the following and let me know how it goes.

  • Can you insert options into slider and use it inside shortcodes?
  • SlidesJS slider does not play automatically. Can you find how it can be set to slide automatically?

Looking forward to your answers.

Wrap Up

In this part I was forced to omit explanations for each and every code line due to the complexity it can cause for you as web designers. Your focus should be on using this code and creating different types of sliders as well as other components without worrying too much about the complex codes.

By now you should be able to insert another type of slider into the same plugin with the instructions I gave on the Things to Focus sections.

Let me know how it goes and any help you need in making different sliders using this plugin.

Enhancing WordPress Plugins with Add On Features

Here we are going to complete the basic structure of a plugin by learning how to create a WordPress plugin settings page for our slider. Stay tuned as settings are an important part in customizing the functionality of a Plugin. So let’s get started.

Download Source Files.

Note that in order to test the final version, you will have to install it on your WordPress installation.

What is a WordPress Plugin Settings Page?

In any kind of system, configuration settings define the data which needs to be initiated before the system starts working. These settings determine the functionality and features of your system.

Consider the SlidesJS slider, which we developed through the last three parts. We didn’t have any configuration settings and hence we had to stick with the default features. This slider is not going to suit every WordPress theme and not every designer is going to like the default features.

So it’s ideal to have some options which can change the existing behavior of the plugin to suit the requirements of each user. Let’s assume we need to auto play the slider or change the existing transition interval as it is too slow; unfortunately we don’t have settings at the moment and we need to use what the plugin offers.

In the next few sections we will be adding options in different ways to allow us to customize the plugin.

Planning Settings for SlidesJS Slider

SlidesJS comes with dozens of configuration options on its own. In this tutorial I am going to use a few of these configurations to help you understand the plugin settings creation process on WordPress.

Following is a list of configurations which we are going to implement in this tutorial.

  • Play button – Sliders can contain a button for play/pause functionality. We can enable or disable play button in the common settings page.
  • Autoplay – Most sliders will play automatically when they’re loaded. We can enable or disable autoplay in the common settings page.
  • Effects – Sliders have multiple transition effects. Currently we are using the slide effect. We can allow the user to choose the effect from the common settings page.
  • Transition Duration – is the time between slide transitions. Sometimes we need it to transition faster or slower depending on the type of content. We can use the common settings page to configure transition duration.

Now we have identified the necessary settings to be included in the plugin. Let’s move forward by building the common plugin settings page.

Creating the Admin Menu Page for Plugin Settings

WordPress does not come with specially designed pages for plugin options. We can either use the admin menu page or the options page to make the HTML forms required for configuring options. I am going to use the admin menu page to implement the options.

First we have to use the following code to add the page to the left menu.

add_action('admin_menu', 'fwds_plugin_settings');

function fwds_plugin_settings() {

    add_menu_page('1stWD Slider Settings', '1stWD Slider Settings', 'administrator', 'fwds_settings', 'fwds_display_settings');

}

We have to use the action called admin_menu to add a new menu item and fwds_plugin_settings is the name of the function to add the page.

Inside the function we can use the built-in add_menu_page to create the menu item. You will be able to see a screen like the following, once you include the above code in the plugin.

WordPress Plugin Development from Scratch, Part 4/4: Settings Page

Even though it’s not mandatory, it’s ideal to have a general idea about the parameters of the add_menu_page function.

  • Parameter 1 (1stWD Slider Settings) – is the title used in your HTML page.
  • Parameter 2 (1stWD Slider Settings) – is the title used for the menu item on the left menu.
  • Parameter 3 (administrator) – is the capability needed to add the page. You can keep it as administrator in most of the cases..
  • Parameter 4 (fwds_settings) – is a unique key used for the menu item.
  • Parameter 5 (fwds_display_settings) – is the function name used to implement the HTML form.

Having learned about the parameters, let’s implement the HTML form required for adding settings fields.

function fwds_display_settings() {

    $slide_effect = (get_option('fwds_effect') == 'slide') ? 'selected' : '';

    $fade_effect = (get_option('fwds_effect') == 'fade') ? 'selected' : '';

    $interval = (get_option('fwds_interval') != '') ? get_option('fwds_interval') : '2000';

    $autoplay  = (get_option('fwds_autoplay') == 'enabled') ? 'checked' : '' ;

    $playBtn  = (get_option('fwds_playBtn') == 'enabled') ? 'checked' : '' ;

    $html = '</pre>
<div class="wrap"><form action="options.php" method="post" name="options">
<h2>Select Your Settings</h2>
' . wp_nonce_field('update-options') . '
<table class="form-table" width="100%" cellpadding="10">
<tbody>
<tr>
<td scope="row" align="left">
 <label>Slider Effect</label>
<select name="fwds_effect"><option value="slide">Slide</option><option value="fade">Fade</option></select></td>
</tr>
<tr>
<td scope="row" align="left">
 <label>Enable Auto Play</label><input type="checkbox" name="fwds_autoplay" value="enabled" /></td>
</tr>
<tr>
<td scope="row" align="left"><label>Enable Play Button</label><input type="checkbox" name="fwds_playBtn" value="enabled" /></td>
</tr>
<tr>
<td scope="row" align="left">
 <label>Transition Interval</label><input type="text" name="fwds_interval" value="' . $interval . '" /></td>
</tr>
</tbody>
</table>
 <input type="hidden" name="action" value="update" />

 <input type="hidden" name="page_options" value="fwds_autoplay,fwds_effect,fwds_interval,fwds_playBtn" />

 <input type="submit" name="Submit" value="Update" /></form></div>
<pre>
';

    echo $html;

}

First I have used five variables to get the current values of the settings from database. Initially all of those options will be empty and hence I have added default values as necessary. We can use get_option function to retrieve any option value from the database.

Then the most important thing is the form action. Since we are creating an options page, we can use options.php as the action.

Afterwards we create the necessary fields for our configuration settings. The transition effect is designed as a dropdown box to contain the two effects in the SlidesJS slider. We use checkboxes for both autoplay and play button options. A textbox will be used for transition duration.

In a normal scenario we need to save these values manually once the form is submitted. Fortunately WordPress provides a built-in method for updating options without using any additional code. All you have to do is specify two hidden fields in your form with predefined values.

The first field should be named action while its value should be update. The next hidden field should be named page_options. Its value should contain all the field names in the form separated by commas.

That’s it. Once you enter values and hit the update button, values will be saved automatically and your options page should look something similar to the following.

WordPress Plugin Development from Scratch, Part 4/4: Settings Page

Now we have the values of configuration options to initialize the slider.Final task will be to use these settings to initialize the slider dynamically.

Initializing Slider with Dynamic Configuration Settings

Our slider initialization code resides in the slidesjs.initialize.js file. We need a method to pass the dynamically configured settings into the JavaScript file, so let’s see how we can alter the fwds_scripts function and pass the data to the JavaScript file.

function fwds_scripts() {
    wp_enqueue_script('jquery');
    wp_register_script('slidesjs_core', plugins_url('js/jquery.slides.min.js', __FILE__), array("jquery"));
    wp_enqueue_script('slidesjs_core');

    wp_register_script('slidesjs_init', plugins_url('js/slidesjs.initialize.js', __FILE__));
    wp_enqueue_script('slidesjs_init');

    $effect      = (get_option('fwds_effect') == '') ? "slide" : get_option('fwds_effect');
    $interval    = (get_option('fwds_interval') == '') ? 2000 : get_option('fwds_interval');
    $autoplay    = (get_option('fwds_autoplay') == 'enabled') ? true : false;
    $playBtn    = (get_option('fwds_playbtn') == 'enabled') ? true : false;
    $config_array = array(
            'effect' => $effect,
            'interval' => $interval,
            'autoplay' => $autoplay,
            'playBtn' => $playBtn
        );

    wp_localize_script('slidesjs_init', 'setting', $config_array);

}

The initial part of including scripts will be similar to the code we used in the previous part. First we need to get the configured option values from the database using the get_option function, as we used earlier. Then we have to assign all the values into an array to be passed into the script.

WordPress provides a method called wp_localize_script for passing values to JS files. First parameter of this function is the key used for the required js file. Then we can define the variable name, which is used to access the values from JavaScript file. Finally we pass the option values array to the function.

Then we need to alter the initialization script as following in order to accept values dynamically.

jQuery("#slides").slidesjs({
    navigation: false,
    play: {
      active: setting.playBtn,
      effect: setting.effect,
      auto: setting.autoplay,
      interval: setting.interval,
    },
  });
});

We can configure all the options we used in the options page using the play array defined in the SlidesJS configuration. You can access any value using the setting variable.

The initial plan also included the configurations for slider dimensions, but the width and height configurations in SlidesJS don’t work as documented. Dimensions are assigned from both CSS and plugin files making it hard to enable configuration and hence I have omitted it here.

Now we have completed our plugin with some basic configuration options. The final output of the slider will look like the following image once you enable all the options, including the play button.

WordPress Plugin Development from Scratch, Part 4/4: Settings Page

Finished!

Throughout this series, we learned how you can build a design based WordPress plugin from scratch. Now you should have a much better understanding of developing a simple plugin. Now it’s time for you to move forward with the examples. Unless you practice these theories, you wont become a good plugin developer. So make sure to try out different sliders and configure different options to get a better understanding of plugin development.

Things to Take Away

We discussed lots of theories and techniques in detail. Now I’ll summarize the most important things to take away from this plugin development series in order to get you started practicing. You should know:

  • How to define a plugin and the file structure
  • How to include CSS and JavaScript files and pass the data dynamically
  • Using Custom Post Types to create different types of data for components
  • How to work with extra fields inside custom posts
  • How to create a plugin options page

I suggest you try these techniques for at least another three sliders to understand the concepts. Once you complete that task you can move onto creating something like an accordion, tabs or another similar component using the same techniques.

This post may contain affiliate links. See our disclosure about affiliate links here.