December 27th in Wordpress by .

Tutorial: How to write a WordPress Plugin?

 

WordPress is not just a blogging platform and it is such a powerful CMS with unlimited capabilities, besides having a huge user base. Almost anything can be scripted with wordpress. You can extend wordpress either by means of plugin or by a theme.

In this tutorial, i will show you how to write a Hello World wordpress plugin, which unlike many believe is surprisingly easy, once you understand the very fundamentals. All you need to have is a basic knowledge of php scripting.

Before we move on coding a plugin, please make sure you remember the following coding practices.

1. Always you chose a unique name to your plugin so that it doesnt collide with names used in other plugins.

2. Make sure you comment wherever and whenever necessary in the code.

3. You will to test the plugin in your localhost (using xampp) along with latest version of wordpress.

Plugin Files & Names

Assigning unique names, documenting and organizing the plugin files is very important part of plugin creation.

Although wordpress allows you to place the plugin php file directly into the wp-content/plugins folder, for a good plugin developer you will need to create a folder named hello-world and within place readme.txt and hello-world.php.

The readme.txt contains information about your plugin and can come in handy when you submit your plugin wordpress SVN plugin repository. See the readme sample.

Go ahead and create these files and we will add the content to these files later.

The Plugin Basics

The heart of a wordpress plugins is the below 2 functions (commonly called `hooks`)

add_action ($tag, $func) documentation
add_filter ($tag,$func) documentation

It is very important to know the difference between the above functions.

  • add_action –> does an action at various points of wordpress execution
  • add_filter –> does filtering the data (eg. escaping quotes before mysql insert, or during output to browser.

Refer to the WordPress Plugin API for more better understanding.

Plugin Information

Open your hello-world.php and in the first line, add this commented plugin information to your file.

<?php
/*
Plugin Name: Hello-World
Plugin URI: http://yourdomain.com/
Description: A simple hello world wordpress plugin
Version: 1.0
Author: Balakrishnan
Author URI: http://yourdomain.com
License: GPL
*/
?>

Save this php file,

  • Place the plugin folder to wordpress > wp-content > plugins,
  • Go to your wordpress admin > plugins and you will see the new plugin listed, waiting to get activated.

simple ain’t it?

But this plugin had to do something right?

Why not we make it print  “Hello World” when we call it from wordpress theme template files.

for that we write the code using add_action below the commented plugin information in the hello-world.php

<?php
/*
Plugin Name: Hello-World
Plugin URI: http://yourdomain.com/
Description: A simple hello world wordpress plugin
Version: 1.0
Author: Balakrishnan
Author URI: http://yourdomain.com
License: GPL
*/
/* This calls hello_world() function when wordpress initializes.*/
/* Note that the hello_world doesnt have brackets.
add_action('init','hello_world');
function hello_world()
{
echo "Hello World";
}
?>

Thats it! Our Hello World plugin is nearly done and with just few lines of code. When our plugin is activated, add_action command calls our hello_world() function when wordpress starts loading.

Lets Test our Hello World Plugin

We really dont know whether our plugin works or not. To test our plugin, go to plugins, activate the hello-world plugin.

Then open your worldpress theme wp-content > themes > default, open any of index.php, archive.php or single.php and place the following code anywhere.

<?php
if(function_exists('hello_world')) {
hello_world();
}
?>

The key here is function_exists() call which checks whether plugin loaded or not and then allows the hook into the plugin function.  Call to hello_world() in the theme files without checking it, often leads to “Fatal error: call to undefined function” and our blog would crash, if the hello world plugin is not activated or deleted.

If you carefully notice above graphic, see how the hello world appears. Thats the work of our plugin. It WORKS!

Lets take our plugin one step further!

Why not, we build a plugin options page in admin area and provide a backend for plugin users?

Right now, the plugin outputs hello world (its pretty much static) and if somebody wants to output ‘Hello Example’, they need to open the php file and make changes everytime to print different text.

Asking the user to edit plugin files isnt a good idea!  As a wordpress plugin developer, it is you, who has to provide a good wordpress options interface in the wp-admin area.

Writing Plugin Options Page

We now create  Hello World options page in the wordpress admin area.

Here is what we do….

  • When plugin gets activated, we create new database field `wp_hello_world_data` using set_options() function.
  • When plugin gets deactivated, we delete the database field `wp_hello_world_data`
  • We create a options menu for Hello World in WordPress Admin > Settings.
  • We save the user entered data in the wordpress database.
  • We retrieve the data stored in wordpress database and output it using get_options() function.

Why we are creating database field? because the saved data must be saved somewhere? ie. in wordpress database. This way the plugin outputs user entered text, instead of the static “Hello World”.

Activating/Deactivating Plugin

It is very easy to write a function on what plugin does, when it gets activated. WordPress offers 4 very important functions

<?php
/* Runs when plugin is activated */
register_activation_hook(__FILE__,'hello_world_install'); 

/* Runs on plugin deactivation*/
register_deactivation_hook( __FILE__, 'hello_world_remove' );

function hello_world_install() {
/* Creates new database field */
add_option("hello_world_data", 'Default', '', 'yes');
}

function hello_world_remove() {
/* Deletes the database field */
delete_option('hello_world_data');
}

?>

The above code creates the new database field `hello_world_data` using add_options and it runs when we activate the plugin. It has the value ‘default’ since we explicitly define it.

Similarly when the plugin gets deactivated or removed, we need to clean up things, so we remove the created database field using delete_option.

Plugin Settings Page

This is our final step.  All we need to create is plugin settings page in the wordpress admin area.  The settings page will update and save the data to the database field `hello_world_data` which we created while activating the plugin. Be sure to checkout creating options page in wordpress codex.

Here is a very important thing to remember:

The add_action for admin_menu should call a function hello_world_admin_menu() containing add_options_page, which in turn should call a function hello_world_html_code() containing html code. This is how the code should flow! Refer to wordpress administration menus

<?php
if ( is_admin() ){

/* Call the html code */
add_action('admin_menu', 'hello_world_admin_menu');

function hello_world_admin_menu() {
add_options_page('Hello World', 'Hello World', 'administrator',
'hello-world', 'hello_world_html_page');
}
}
?>

The above code, is placed under is_admin() which means it only runs in the wordpress admin area.

The below function has the html code for the settings page, containing the form and notice how the php tag is split to accomodate the html code.

and the coding part is..

<?php
function hello_world_html_page() {
?>
<div>
<h2>Hello World Options</h2>

<form method="post" action="options.php">
<?php wp_nonce_field('update-options'); ?>

<table width="510">
<tr valign="top">
<th width="92" scope="row">Enter Text</th>
<td width="406">
<input name="hello_world_data" type="text" id="hello_world_data"
value="<?php echo get_option('hello_world_data'); ?>" />
(ex. Hello World)</td>
</tr>
</table>

<input type="hidden" name="action" value="update" />
<input type="hidden" name="page_options" value="hello_world_data" />

<p>
<input type="submit" value="<?php _e('Save Changes') ?>" />
</p>

</form>
</div>
<?php
}
?>

You must remember 2 things in the above code.

1. Specify the database field we created before in the input text box as `hello_world_data`

<input name="hello_world_data" type="text" id="hello_world_data"
value="<?php echo get_option('hello_world_data'); ?>" />

2. If your form has number of fields (like textbox, selectbox etc), all those should be listed in the value field of page_options, separated by commas. For more information, refer to wordpress documentation

<input type="hidden" name="page_options" value="hello_world_data" />
Now, the plugin outputs whatever the user specifies in the hello world settings page.

Thats it! Our plugin is READY!

Dont forget to add documentation to readme.txt.

Enjoy!
___________________________________________

Save time in your website design using these 20 really useful cheatsheets for web designers.
Testking offers latest 70-432 questions and 70-620 study guide to help its candidates pass 70-640 exam on first try.

Similar Posts:

168 Comments

  • Patrick
    January 3, 2010
    • umer
      May 28, 2011
      • Lalit vishwakarma
        October 4, 2012
  • Girish
    January 5, 2010
    • JM
      August 1, 2012
  • Mat Green
    January 14, 2010
    • Mat Green
      January 14, 2010
      • pbu
        January 14, 2010
        • Mat Green
          January 15, 2010
    • manish goyal
      November 28, 2012
  • akhil
    January 14, 2010
  • Laki
    January 30, 2010
    • sk8te
      February 22, 2010
      • CJ
        May 6, 2010
        • CJ
          May 8, 2010
          • akasuna
            October 18, 2010
          • Jim
            May 7, 2011
          • delaram
            February 5, 2012
    • Sharif
      January 14, 2012
  • Best WP Plugins
    February 23, 2010
  • Asad
    April 12, 2010
  • karuppasamyp
    April 27, 2010
  • zacharyrs
    May 14, 2010
  • Adam
    June 17, 2010
  • Adam
    June 18, 2010
  • Dinesh
    July 15, 2010
  • Vator
    August 4, 2010
  • Alvin John
    August 27, 2010
  • jkvirtudazo
    September 15, 2010
    • pbu
      September 15, 2010
      • jkvirtudazo
        September 15, 2010
        • LKM
          February 3, 2012
        • Art of living realty
          June 22, 2012
  • RK
    October 14, 2010
  • RK
    October 14, 2010
  • akasuna
    October 18, 2010
  • jhon
    December 8, 2010
  • Mister X
    December 29, 2010
  • starjahid
    January 1, 2011
  • BelloWeb
    January 18, 2011
  • medical assistant
    February 23, 2011
  • Malin D
    February 25, 2011
    • Malin D
      March 7, 2011
      • mono
        October 6, 2011
      • mtijn
        December 18, 2011
      • paul
        August 19, 2012
  • Kamol
    February 28, 2011
  • MY Photography
    March 2, 2011
  • Nice
    March 4, 2011
  • John
    March 6, 2011
  • hi
    March 21, 2011
  • Krishnan
    March 24, 2011
  • Dolendro
    March 25, 2011
  • kasuri
    March 25, 2011
  • hero
    March 29, 2011
  • ssrawat
    April 8, 2011
  • Brian Lawrence
    April 9, 2011
  • ashok
    April 15, 2011
    • ashok
      April 15, 2011
  • ASHOK
    April 16, 2011
  • waseem
    April 28, 2011
  • Jim
    May 7, 2011
  • Joomin
    May 15, 2011
    • pbu
      May 15, 2011
  • Andrew
    May 16, 2011
  • crowdsourcing
    May 21, 2011
  • Elliot
    June 8, 2011
    • LKM
      February 3, 2012
      • LKM
        February 3, 2012
        • LKM
          February 3, 2012
          • Tristan Chambers
            April 5, 2012
          • Thea G.
            December 13, 2012
  • Tahir Yasin
    June 21, 2011
  • Okeowo Aderemi
    June 24, 2011
  • Bobo
    July 1, 2011
  • Bobo
    July 2, 2011
  • mockie
    July 2, 2011
  • Bobo
    July 3, 2011
  • Bobo
    July 3, 2011
    • chris
      September 6, 2011
  • Soumen Kundu
    July 9, 2011
  • pawee
    July 11, 2011
  • hamza khan
    July 17, 2011
  • David Wesst
    July 19, 2011
  • Adam
    July 20, 2011
  • quinn
    July 20, 2011
  • Zeaks
    August 8, 2011
  • adrian
    August 18, 2011
  • Ilya
    August 23, 2011
  • Coupon Database
    August 30, 2011
  • pbu
    September 9, 2011
  • Ghazanfar
    September 22, 2011
  • Web Dizajn
    October 6, 2011
    • website
      May 16, 2013
  • mono
    October 6, 2011
  • Sidra Sultana
    October 24, 2011
  • Hari
    November 25, 2011
  • voo
    November 27, 2011
  • Dhara Shah
    December 1, 2011
  • Padma
    December 12, 2011
  • J'Ze
    December 19, 2011
  • AdrianTYC
    December 23, 2011
  • Joe
    December 23, 2011
    • Maria
      August 3, 2012
      • Maria
        August 3, 2012
  • Fawwad Khan
    December 30, 2011
  • Jeyakumar
    January 11, 2012
  • Jeyakumar
    January 11, 2012
    • pv
      April 5, 2012
  • Anubhav Misra
    February 7, 2012
  • Josh
    February 15, 2012
  • Tiberius14
    February 17, 2012
  • Brijesh
    February 18, 2012
  • Andrew
    February 19, 2012
  • ravi
    March 5, 2012
  • Jalal Khan
    March 22, 2012
  • mamaswae
    March 24, 2012
  • Erick Jones
    March 30, 2012
  • Anil kumar
    April 4, 2012
  • Alex
    April 5, 2012
  • Nigam
    April 11, 2012
  • Diana
    April 17, 2012
    • buddy
      April 24, 2012
  • buddy
    April 24, 2012
  • Glekko
    May 11, 2012
  • Reja
    May 15, 2012
  • Sardar
    May 23, 2012
  • Akbar
    May 26, 2012
  • Markus
    June 4, 2012
  • Vijaya Narayanasamy
    June 20, 2012
  • Vijaya Narayanasamy
    June 20, 2012
  • Vijaya Narayanasamy
    June 20, 2012
  • don.Diego
    June 29, 2012
  • dinh vi
    July 14, 2012
  • Dilip
    July 18, 2012
  • Vijaya Narayanasamy
    July 20, 2012
  • Khem
    July 26, 2012
  • manisha
    August 3, 2012
    • website
      May 16, 2013
  • Keyur Panchal
    August 4, 2012
  • Muminul Haque
    August 23, 2012
  • Best Web designer London
    August 29, 2012
  • Sunil sahu
    August 30, 2012
  • me
    September 2, 2012
  • kat mac
    September 11, 2012
    • MadTurki
      September 22, 2012
  • NaukriBox
    September 14, 2012
  • wasi
    September 27, 2012
  • preeti
    September 30, 2012
  • Vamsi
    October 7, 2012
  • Rathod
    October 12, 2012
  • jeyaganesh
    November 8, 2012
  • chandra sekhar
    November 9, 2012
  • Shahzad
    November 14, 2012
  • Rahul Kumar
    November 15, 2012
  • Mohit
    November 21, 2012
  • Uday Augustin
    December 7, 2012
  • Drum
    January 31, 2013
  • David
    February 1, 2013
  • Ashit Kumar
    February 12, 2013
  • Lohith
    March 12, 2013
  • Sandeep pattanaik
    March 26, 2013
  • Rahul
    April 1, 2013
  • shalu
    April 4, 2013
  • Knoje
    April 20, 2013
  • AMIT DAVE
    May 7, 2013

Leave A Comment.






9 − = three

Please wrap all source codes with [code][/code] tags. Powered by