Thursday, July 09, 2015

How to create Plugin in WordPress - I

Here we are going to discuss how we can create simple plugin in Wordpress 1.9.

The process is described below ::

1. We need to create a PHP file, say "xyz.php" inside the wp-content/plugins folder. The name of the file is not important. The Plugin details should be mentioned within a comment inside that file. 

   So, the file may start with the following ::  

   <?php
   /*
   Plugin Name: My TEST Plugin 
   Plugin URI: http://myplugin.com
   Description: This is a TEST Plugin created by Chandan Patra
   Author: Chandan Patra
   Author URI: http://chandanpatra.blogspot.in
   Version: 1.0
   */
 ?>

The above comment has various information about our Plugin. I have given the plugin a name "My TEST Plugin". Check how this will appear in the Plugin section in Wordpress Admin Panel.



2.  We can create a new folder in wp-content/plugins and put the above file inside that also. 
    wp-content/plugins/my_plugin/xyz.php

3. Next, we need to activate our plugin by clicking on the "Activate" link. 
     Note :: Active plugins are listed in serialized form in 'wp_options' table with option name 'active_plugins'.
   
4. Now, let's add some functionality to our plugin. Let's create a small contact form with 2 fields, "Name" and "Email". When user fills up this form and hit the submit button, it generates a mail and sends it to a particular recipient's Email ID. 

   But, how our plugin would get the recipient email address? So, we need to create a Settings screen for our plugin where Admin can configure our plugin to work properly. There, Admin can put the recipient's email address also.

5. Creating a Settings page :: 
   To achieve this, we need to define our custom function (say, my_plugin_works()) which creates the Menu title etc and then add our custom function to a hook called 'admin_menu'. So, just below the Plugin information (as shown in point.1 above) in xyz.php file, we'll add the following code. 
   
   // So, we are adding our custom function
 // 'my_plugin_works' to the 'admin_menu' hook
 add_action('admin_menu','my_plugin_works');

 // Here is the definition of our 
 // custom function
 function my_plugin_works()
 {
    //this is the main item for the menu
    add_menu_page(
        'My Plugin',           //page title
'My Plugin Options',   //menu title
'manage_options',      //capabilities
'my_plugin_opt',       //menu slug
'my_plugin_func'       //function
);
 }

   The above code would create a menu called "My Plugin Option" as shown in the screenshot below.

   We have used the add_menu_page() function which takes 5 parameters as described above. The 3rd parameter should be "manage_options" which lets us  create/change settings within Wordpress Admin Panel. 




6. So, when the "My Plugin Options" menu is clicked, we are redirected to URL : http://127.0.0.1/wp/wp-admin/admin.php?page=my_plugin_opt.
   
   The URL parameter 'my_plugin_opt' is supplied as 4th argument when calling add_menu_page() function. 

7. And when we are redirected to the above URL, the function 'my_plugin_func' is going to be executed and this was passed as 5th argument to add_menu_page() function. So, now we need to define our my_plugin_func() function. Here is the definition ..

<?php
function my_plugin_func()
{
  $message = "";
  $error   = 0;  

?>  
<form method="post">
<table style="width:500px" cellspacing="10" cellpadding="10">
  <tr>
    <td colspan='3' style='font-size:15px;font-weight:bold'>
    My Plugin Settings</span> on your page
    </td>
  </tr>
  <tr>
   <td colspan='3' style='font-size:12px;font-weight:bold'>
   Use shortcode <span style='color:blue;'>[myplugin]</span> on your page
   </td>
  </tr>
  <tr>
   <td>Enter Recipient Email Address </td>
   <td>:</td>
   <td>
     <input type='text' name='email' value="<?php echo get_option('myplugin_recipient_email');?>">
   </td>
  </tr>
  <tr>
   <td colspan='3'><input type='submit' value='Submit' name='btnsubmit'></td>
  </tr>
  <tr>
   <td colspan='3'>
     <span style='color:<?php echo ($error?'red':'green') ;?>'>
   <?php 
     // Shows Message
echo ($message!=""?$message:"");
   ?>
    </span>
   </td>
  </tr>
 </table>
</form>
<?php
}
?>

So, our custom function my_plugin_func() shows a Form where the recipient mail can be entered. Notice the line : 

<input type='text' name='email' value="<?php echo get_option('myplugin_recipient_email');?>">

We have given a name for our settings as 'myplugin_recipient_email'. So, when the above form is shown, it tries to get option from Wordpress. The function  get_option() is a Wordpress function which tries to get 'named' option from DB. Initially, it won't show populate the <input> field, however when we would be able to save the recipient email address as a named option ('myplugin_recipient_email') in database, this <input> field will be successfully populated.

Check, how the form looks like ... 




Now, we need to add functionality to this form so that the recipient email can be saved. So, we are adding the PHP code that will save the Email address in database. Here is the full version of the function my_plugin_func() ::

<?php
function my_plugin_func()
{
  $message = "";
  $error   = 0;  
  // Handle POST
  if(isset($_POST['btnsubmit'])) 
  {
  $email_id = trim($_POST['email']);
  if($email_id!="")
  {
    // Validation
      if( filter_var($email_id, FILTER_VALIDATE_EMAIL) )
      {
update_option('myplugin_recipient_email',$email_id,true);
$message = "The recipient Email saved successfully";
$error   = 0;  
      }
      else
    {
         $message = "Invalid Email Address";
$error   = 1;  
      }
    }
  else
  {
  $message = "Email can not be blank";
  $error   = 1;  
  }
  }
?>  
<form method="post">
 <table style="width:500px" cellspacing="10" cellpadding="10">
  <tr>
    <td colspan='3' style='font-size:15px;font-weight:bold'>
       My Plugin Settings</span> on your page
    </td>
  </tr>
  <tr>
   <td colspan='3' style='font-size:12px;font-weight:bold'>
    Use shortcode <span style='color:blue;'>[myplugin]</span> on your page
   </td>
  </tr>
  <tr>
   <td>Enter Recipient Email Address </td>
   <td>:</td>
   <td>
     <input type='text' name='email' value="<?php echo get_option('myplugin_recipient_email');?>">
   </td>
  </tr>
  <tr>
   <td colspan='3'><input type='submit' value='Submit' name='btnsubmit'></td>
  </tr>
  <tr>
   <td colspan='3'>
     <span style='color:<?php echo ($error?'red':'green') ;?>'>
     <?php 
        // Shows Message
echo ($message!=""?$message:"");
     ?>
  </span>
   </td>
  </tr>
 </table>
</form>
<?php
}
?>

  The POST data handling part is quite simple, it checks the input email address and calls 'update_option()' function to save it under the name 'myplugin_recipient_email'. If the function 'update_option()' does not  find the option 'myplugin_recipient_email' existing, it creates one and save the email address against it.
  
  So, now we have a working settings page, where we can enter and save any email address. Now we have to show a Contact Form at the front-end.

Check the 2nd part of this article here.

No comments: