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

Posted in Plugins, WordPress11 months ago • Written by 15 Comments

Welcome to the final part of our tutorial series on WordPress Plugin Development for Designers. In the last three parts, we discussed the importance of plugins for you as designers and identified a basic structure for design based plugins while integrating a jQuery slider into WordPress.

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

WordPress Plugin Development Series:

(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

Wrap Up

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.

In future tutorials I’ll show you how to use the same codes to create different types of plugins with minimal modifications.

Until then, I hope you will try these theories. Let me know about your experiences, questions, suggestions or any comments regarding this tutorial series.

Looking forward to hearing from you.

If you enjoyed this article, get email updates (it's free).

Join over 77,235 Subscribers Today.

22 Written ArticlesWebsiteGoogle+

Rakhitha Nimesh is a software engineer and writer from Sri Lanka. He likes to develop applications and write on latest technologies. He is available for freelance writing and WordPress development. You can read his latest book on WordPress Web Application Development. He is a regular contributor to 1stWebDesigner, Tuts+ network and Sitepoint network. Make sure to contact him at www.innovativephp.com or follow him on Twitter and Google+

15 Comments Best Comments First
  • Ana

    Friday, May 17th, 2013 14:12

    1

    I have to say, I am happy that we got to the last part, been waiting on it for a while. Excellent series for web designers who are new to plugin development.
    I am just curios why the options for uploading slides isn’t in admin settings for the plugin? I kinda think it would be logical to include it in there instead separately. Or is it a bit too much for first time plugin development?

    +5
    • Rakhitha Nimesh

      Saturday, May 18th, 2013 22:01

      2

      Hi Ana

      Thanks for your kind words. Last part took some time to publish and thanks for being patient.

      Do you mean that we should get the slides uploading to the settings page instead of custom post types?

      If we get the slide uploading to admin settings, we can only upload slides for single slider. we have to write lot of additional code to make it work for multiple sliders. When we use custom post types, we can easily upload slides for multiple sliders.

      Settings page should be used to configuration of the plugin rather than dynamically changing data.

      Let me know if you have more concerns and how it goes with the plugin.

      0
  • Deepthi

    Wednesday, July 31st, 2013 23:59

    14

    Hai Rakhitha Nimesh,

    First of all i would like to thank you for this wounder full series of tutorial.

    i am fresher to this field and would like to develop a plugin on mail contact importer

    i hope you would help me for the best results

    Thanks a lot in advance………

    +2
  • Th.

    Friday, July 5th, 2013 02:46

    9

    Hi, Rakitha,

    your tutorial is just what I looked for. Thank you! But I found one mistake. If you have special national characters in the filename (like äöü of the German language) and publish this image, the special character gets converted to a unicode-like string. For example ö.jpg converts to u00f6.jpg

    +1
  • Jim Console

    Saturday, June 15th, 2013 11:38

    8

    Rak,
    Thank you for putting this all together. You have a knack for presenting thoroughly just enough info to get real results. I was a developer years ago but never used PHP or WP and this series got me to put a few things together in my head so I can actually build something – most other tuts describe how to build the headers and leave you as soon as function coding starts. I WILL be spending some quality time with your WP blog section.

    Thanks again…

    +1
  • purushothama kumar

    Tuesday, July 23rd, 2013 06:20

    12

    hai..am purushothama kumar from hyderabad(india)..working as a php,wordpress,zend developer..i hope you are doing well..just i have seen your website..looking very nice explanation..if you dont mind can you please give me your gmail id??

    0
  • Peter

    Thursday, May 30th, 2013 17:12

    4

    I m creating my first theme from scratch and trying to build a full screen background image jquery slider feature into it.
    This tutorial is a great guideline. Thankx !

    wp_localize_script is the glue : )

    0
    • Rakhitha Nimesh

      Sunday, June 2nd, 2013 21:36

      5

      Hi Peter

      Thank you very much for your interest in this tutorial series.

      Indeed, wp_localize_script is pretty simple and useful. There was a time I didn’t know about that function and it was awful experience passing data to js files.

      Let us know how the full screen slider is implemented on your site.

      0
  • Jacob Obama

    Tuesday, May 21st, 2013 05:16

    3

    Hi Rakhita Nimesh great post, and i am completely agreed with Ana. Ana said that your tutorial is best for any newbie on plugin development. That is true and more thing is that your article consist nice uses of an examples and contents.

    0
    • Rakhitha Nimesh

      Sunday, June 2nd, 2013 21:37

      6

      Hi Jacob

      Thank you very much for appreciating my work. I always like to go with practical tutorials rather than focusing on boring theories.

      So did you have any sites where you have implemented such sliders?

      0
  • Chris

    Thursday, June 6th, 2013 01:01

    7

    Hi,

    This was a great tutorial series. I’m getting an error with debug set to true in wp_congfig file, options.php was called with an argument that is deprecated since version 2.7! The fwds_autoplay setting is unregistered. Unregistered settings are deprecated. See http://codex.wordpress.org/Settings_API in /Applications/XXXXX/htdocs/XXXXXX/testing/wp-includes/functions.php on line 2923.

    Thanks

    0
  • Alexis

    Monday, July 22nd, 2013 16:39

    11

    Hi,
    Thank you for this great tutorial. I’m getting close to obtain what I wanted.

    I’ve followed the main steps and I think I could give some tips for a better implementation :

    - When you register the custom post type, you can use the custom_post_type_generator from http://generatewp.com/. (it’s not my own website and I use it very often to create my custom post types because it is very well built, especially for the menu/alias names, i hope this link will not be considered as spam.)

    - You can easily add custom icons to your custom post type, using the code following :

    function _YOUR_PREFIX_add_post_type_icons() {
    ?>

    #menu-posts-YOUR_CUSTOM_POST_TYPE .wp-menu-image {
    background: url() no-repeat 6px -22px !important;
    }
    #menu-posts-YOUR_CUSTOM_POST_TYPE:hover .wp-menu-image, #menu-posts-fichier.wp-has-current-submenu .wp-menu-image {
    background-position:6px 3px!important;
    }
    #icon-edit.icon32.icon32-posts-YOUR_CUSTOM_POST_TYPE {
    background: url() no-repeat !important;
    }

    <?php
    }
    add_action( 'admin_head', '_YOUR_PREFIX_add_post_type_icons' );

    - Finally, for the setting page : personally, i didn’t like the plugins which install a new page for the settings. We already have a menu entry for the custom post type, it’s useless to make another menu entry again, and if all plugins do that, you’ll have quickly too much menus.
    I’ve used instead the function “add_submenu_page” (here in the codex : http://codex.wordpress.org/Function_Reference/add_submenu_page), to place it on my custom post type submenu.

    Thank again for the demo !

    0
  • Jan

    Wednesday, July 17th, 2013 02:56

    10

    To make the script more comprehensible for beginners I’d suggest you remove the ternary operators from line 9 to 12 of your fwds_scripts function.

    get_option has a 2nd parameter that can be used to set the default value in case nothing is returned (see http://codex.wordpress.org/Function_Reference/get_option).

    $effect = get_option(‘fwds_effect’, ‘slide’);
    $interval = get_option(‘fwds_interval’, 2000);
    $autoplay = get_option(‘fwds_autoplay’, ‘enabled’);
    $playbtn = get_option(‘fwds_playbtn’, ‘enabled’);

    0
  • Deepthi

    Wednesday, July 31st, 2013 01:50

    13

    Hi Rakhita Nimesh,

    Thanks a lot for this tutorial series it helps a lot for me. i hope so your adventure in this plugin development will continues and we will get more tutorial in feature.

    i am fresher to this and i am trying to develop a mail contact importer plugin

    i hope so you will guide me for the best results.

    0
  • Astha Chauhan

    Thursday, August 8th, 2013 02:44

    15

    Very learning tutorial, even as a beginner of wordpress I found it easy to understand and developed my custom plugin to handle dynamic slider.
    Kindly send me links of such type of tutorial if possible. Thanks Rakitha.

    0
  • Astha Chauhan

    Thursday, August 8th, 2013 02:44

    15

    Very learning tutorial, even as a beginner of wordpress I found it easy to understand and developed my custom plugin to handle dynamic slider.
    Kindly send me links of such type of tutorial if possible. Thanks Rakitha.

    0
  • Deepthi

    Wednesday, July 31st, 2013 23:59

    14

    Hai Rakhitha Nimesh,

    First of all i would like to thank you for this wounder full series of tutorial.

    i am fresher to this field and would like to develop a plugin on mail contact importer

    i hope you would help me for the best results

    Thanks a lot in advance………

    +2
  • Deepthi

    Wednesday, July 31st, 2013 01:50

    13

    Hi Rakhita Nimesh,

    Thanks a lot for this tutorial series it helps a lot for me. i hope so your adventure in this plugin development will continues and we will get more tutorial in feature.

    i am fresher to this and i am trying to develop a mail contact importer plugin

    i hope so you will guide me for the best results.

    0
  • purushothama kumar

    Tuesday, July 23rd, 2013 06:20

    12

    hai..am purushothama kumar from hyderabad(india)..working as a php,wordpress,zend developer..i hope you are doing well..just i have seen your website..looking very nice explanation..if you dont mind can you please give me your gmail id??

    0
  • Alexis

    Monday, July 22nd, 2013 16:39

    11

    Hi,
    Thank you for this great tutorial. I’m getting close to obtain what I wanted.

    I’ve followed the main steps and I think I could give some tips for a better implementation :

    - When you register the custom post type, you can use the custom_post_type_generator from http://generatewp.com/. (it’s not my own website and I use it very often to create my custom post types because it is very well built, especially for the menu/alias names, i hope this link will not be considered as spam.)

    - You can easily add custom icons to your custom post type, using the code following :

    function _YOUR_PREFIX_add_post_type_icons() {
    ?>

    #menu-posts-YOUR_CUSTOM_POST_TYPE .wp-menu-image {
    background: url() no-repeat 6px -22px !important;
    }
    #menu-posts-YOUR_CUSTOM_POST_TYPE:hover .wp-menu-image, #menu-posts-fichier.wp-has-current-submenu .wp-menu-image {
    background-position:6px 3px!important;
    }
    #icon-edit.icon32.icon32-posts-YOUR_CUSTOM_POST_TYPE {
    background: url() no-repeat !important;
    }

    <?php
    }
    add_action( 'admin_head', '_YOUR_PREFIX_add_post_type_icons' );

    - Finally, for the setting page : personally, i didn’t like the plugins which install a new page for the settings. We already have a menu entry for the custom post type, it’s useless to make another menu entry again, and if all plugins do that, you’ll have quickly too much menus.
    I’ve used instead the function “add_submenu_page” (here in the codex : http://codex.wordpress.org/Function_Reference/add_submenu_page), to place it on my custom post type submenu.

    Thank again for the demo !

    0
  • Jan

    Wednesday, July 17th, 2013 02:56

    10

    To make the script more comprehensible for beginners I’d suggest you remove the ternary operators from line 9 to 12 of your fwds_scripts function.

    get_option has a 2nd parameter that can be used to set the default value in case nothing is returned (see http://codex.wordpress.org/Function_Reference/get_option).

    $effect = get_option(‘fwds_effect’, ‘slide’);
    $interval = get_option(‘fwds_interval’, 2000);
    $autoplay = get_option(‘fwds_autoplay’, ‘enabled’);
    $playbtn = get_option(‘fwds_playbtn’, ‘enabled’);

    0
  • Th.

    Friday, July 5th, 2013 02:46

    9

    Hi, Rakitha,

    your tutorial is just what I looked for. Thank you! But I found one mistake. If you have special national characters in the filename (like äöü of the German language) and publish this image, the special character gets converted to a unicode-like string. For example ö.jpg converts to u00f6.jpg

    +1
  • Jim Console

    Saturday, June 15th, 2013 11:38

    8

    Rak,
    Thank you for putting this all together. You have a knack for presenting thoroughly just enough info to get real results. I was a developer years ago but never used PHP or WP and this series got me to put a few things together in my head so I can actually build something – most other tuts describe how to build the headers and leave you as soon as function coding starts. I WILL be spending some quality time with your WP blog section.

    Thanks again…

    +1
  • Chris

    Thursday, June 6th, 2013 01:01

    7

    Hi,

    This was a great tutorial series. I’m getting an error with debug set to true in wp_congfig file, options.php was called with an argument that is deprecated since version 2.7! The fwds_autoplay setting is unregistered. Unregistered settings are deprecated. See http://codex.wordpress.org/Settings_API in /Applications/XXXXX/htdocs/XXXXXX/testing/wp-includes/functions.php on line 2923.

    Thanks

    0
  • Peter

    Thursday, May 30th, 2013 17:12

    4

    I m creating my first theme from scratch and trying to build a full screen background image jquery slider feature into it.
    This tutorial is a great guideline. Thankx !

    wp_localize_script is the glue : )

    0
    • Rakhitha Nimesh

      Sunday, June 2nd, 2013 21:36

      5

      Hi Peter

      Thank you very much for your interest in this tutorial series.

      Indeed, wp_localize_script is pretty simple and useful. There was a time I didn’t know about that function and it was awful experience passing data to js files.

      Let us know how the full screen slider is implemented on your site.

      0
  • Jacob Obama

    Tuesday, May 21st, 2013 05:16

    3

    Hi Rakhita Nimesh great post, and i am completely agreed with Ana. Ana said that your tutorial is best for any newbie on plugin development. That is true and more thing is that your article consist nice uses of an examples and contents.

    0
    • Rakhitha Nimesh

      Sunday, June 2nd, 2013 21:37

      6

      Hi Jacob

      Thank you very much for appreciating my work. I always like to go with practical tutorials rather than focusing on boring theories.

      So did you have any sites where you have implemented such sliders?

      0
  • Ana

    Friday, May 17th, 2013 14:12

    1

    I have to say, I am happy that we got to the last part, been waiting on it for a while. Excellent series for web designers who are new to plugin development.
    I am just curios why the options for uploading slides isn’t in admin settings for the plugin? I kinda think it would be logical to include it in there instead separately. Or is it a bit too much for first time plugin development?

    +5
    • Rakhitha Nimesh

      Saturday, May 18th, 2013 22:01

      2

      Hi Ana

      Thanks for your kind words. Last part took some time to publish and thanks for being patient.

      Do you mean that we should get the slides uploading to the settings page instead of custom post types?

      If we get the slide uploading to admin settings, we can only upload slides for single slider. we have to write lot of additional code to make it work for multiple sliders. When we use custom post types, we can easily upload slides for multiple sliders.

      Settings page should be used to configuration of the plugin rather than dynamically changing data.

      Let me know if you have more concerns and how it goes with the plugin.

      0

Comments are closed.

67.202.56.112 - unknown - unknown - US