WordPress Plugin Development from Scratch

Things to Focus on:
In this part we completed the slider functionality. Now its dynamic and effective to suit various types of sections in your web pages.
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.

wpdd_part3_7

Following is a list of possible things we can do inside plugin activation/deactivation.
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.

  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 Source Files.

What to Expect from this Course

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.
wp1stw2d copy
So it’s important to know the basic structure,initial components and functions of a plugin to get things started.

What Can You Expect From Us?

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

Understanding WordPress Plugin Structure

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.
Things to Take Away

What are the prerequisites?

Now it’s your turn.

Should You Create Plugins from Scratch?

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

Components of WordPress Plugin

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.
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; }

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> ‘; }

For the moment just define these hooks with plugin specific activation and deactivation functions and execute necessary codes inside the function.
If attributes are supplied with shortcodes, default value will be replaced by passes value. Finally you can access these attributes using $name and $age.
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.
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.
<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>

Now the question is: do you have a future as a static website designer?
wpbs_09
[my_advanced_shortcode name=”Nimesh” age=”27″] Description about me [/my_advanced_shortcode]

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.
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; }

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.
function fwds_slider_activation() { } register_activation_hook(__FILE__, ‘fwds_slider_activation’); function fwds_slider_deactivation() { } register_deactivation_hook(__FILE__, ‘fwds_slider_deactivation’);

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.
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.

Creating Plugin File

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.
Until then I would like to suggest following resources to get an idea about the contents in the next part of this tutorial series.
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.
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.
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.
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.
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.
Following screen shows the list of folders available inside wp-content folder.
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.
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.
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.

  • 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.

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.
Let me know how it goes and any help you need in making different sliders using this plugin.
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.

WordPress Plugin Activation and Deactivation

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.
function my_advanced_shortcode_handler( $atts, $content = null ) { extract( shortcode_atts( array( ‘name’ => ‘Rakhitha’, ‘age’ => ’20’ ), $atts ) ); echo $name; echo $age; echo $content; }

Things to Focus on:
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.
Let me know about the type of sliders you tried and any difficulties you faced in applying the discussed technique.
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.
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.
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.
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.

Why Do We Use Activation/Deactivation Hooks

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 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.

  • 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.

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>”; }

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:

Coming Up

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.
Having learned about the parameters, let’s implement the HTML form required for adding settings fields.

  • Writing a Plugin
  • WordPress Shortcode API

We can create basic plugins without considering activation and deactivation functions. But advanced plugin will require these functions to provide additional features.
wpbs_03
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.
Now, here’s a challenge to you:

Basics for Creating WordPress Plugin Template

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.
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.
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); }

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.

What is a WordPress Plugin Settings Page?

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 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.
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.
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.

Planning Settings for SlidesJS Slider

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.
Back-end of the Plugin

  • 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.

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.

Creating the Admin Menu Page for Plugin Settings

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.
Download Source Files.
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.
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.
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.
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.

  • 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.

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.
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.
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’); }

Download the Source Files.
What about sizes, effects, speeds of sliders?
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.
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.
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); }

Let’s discuss more on plugin activation.

Initializing Slider with Dynamic Configuration Settings

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.
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; } }

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.
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.
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.

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>’; }

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.
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.

Finished!

wpbs_06
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; }

<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>

wpdd_part3_4

Posted by WordPress Guru