What you will learn

What are Plugins?

With WordPress plugins, we can customize, modify and enhance a WordPress site. It is not a good idea to change core WordPress files as it may break the site. So We use plugins for doing this.

Creating a simple plugin

Step 1: Create a folder inside your wordpress file directory wp-content/Plugin directory. As an example, we are creating a plugin folder exampleplugin. Inside that folder create a file exampleplugin.php
Paste the following file to your exampleplugin.php file and you are ready to go.

/*
Plugin Name: Example Plugin 
Description: This plugin is to learn the basics of Plugin Development.
Author: Kritika Shrivastava
Version: 1.6
Author URI:http://happinessmultiplied.com/
*/

Go to wp-admin click on plugins and you will immediately see a plugin named exampleplugin here. You can activate your plugin from here and modify your plugin as per your need.
Wordpress PLugin Development

Key Points:

  • Notice the Plugin name and description is same as given in the header of plugin file So it looks like a complete plugin now. When you click activate you will see your plugin gets activated.
  • Plugin Naming Guidelines: Plugin name should match the main plugin file and main plugin folder. Do some research before deciding on the plugin name to avoid conflict with other plugins.
  • The code that you have written is actually a comment and is not visible directly to admin.

Congrats!!! You have already created your first plugin. That simple! Cheers!!

Not let us dig deep into this to make a plugin that actually does something.

What are hooks?

Hooks are important for plugin development, it allows to extend, modify or remove core functionality of WordPress.
There are two types of Hooks

  • Actions
  • Filter

Actions: An Action Hook is PHP function that enables to run custom code at a specific point during the execution of WordPress.
As an example, we can use actions to do various things like write to file, echo something, or edit the database.

Filter: Filter hook is to modify data during the execution of WordPress.
We can use custom filters to replace code from existing actions.

Understanding Actions and Filter with an example

Let us create a simple function for sending an email. Open exampleplugin.php file created previously and copy the following code.
/* Check */

function explugin_action_hook_explain(){
wp_mail('test@example.com', 'Subject', 'Message to send');
}
add_action('init', 'explugin_action_hook_explain');
  1. PHP function explugin_action_hook_explain execute when a particular WordPress event occurs.
  2. Use add_action() function to hook this function to event.
  3. Note: The first parameter here is Hook and the second parameter is the name of the callback function. We have registered the function with init hook. The email will be sent every time WordPress executes. Have a look at WordPress docs to know in what sequence hooks are executed.

    Example using filter hook:

    function explugin_filter_hook_example($content){
    	$content = $content . '

    Add your custom content here

    '; return $content; } add_filter('the_content', 'explugin_filter_hook_example');

    Here we will filter the content variable. The content variable is passed to a function and we will add some custom content to it and return the content Variable.
    Then we register the function with a content hook, our custom content will append to the content of every post.

    Key points:

    • In the same way, we can modify any data that is required and can edit WordPress core functionality.
    • We can create our own custom hooks to WordPress
    • We can remove action and filter hook when required.

    Plugin Activation and Deactivation

    We have two important hooks that are major for creating your own wordpress plugin.

    1. register_activation_hook()
    2. register_deactivation_hook()

    To activate Plugin :

    register_activation_hook() This hooks runs when a plugin is activated from WordPress admin. It is good for doing things like creating database tables or many other things that need to be done when a plugin is activated.
    Example:

    function create_ads(){
    	if(!current_user_can('activate_plugins')) return;
    
    	global $wpdb;
                 $wpdb->query("CREATE TABLE IF NOT EXISTS ".$wpdb->prefix."video(
    	  			 `pk` int(255) NOT NULL AUTO_INCREMENT,
    	  			 `video` varchar(255) NOT NULL,
    	  			 `type` varchar(255) NOT NULL,
    	  			 PRIMARY KEY (`pk`)
    				)");
    }
    
    register_activation_hook(__FILE__,'create_ads');
    

    Run this code to your plugin file and you will see a new table in your database wp_video
    The first parameter __FILE__ here is a path of current files, and the second parameter is the name of the callback function.
    Inside the function, we check if the user has the privilege to activate the plugin. If he has the when the plugin is activated it will create a table in the database.

    To deactivate Plugin : register_deactivate_hook() :

    It will activate when the plugin is deactivated. We don’t want all the database tables created for a specific plugin and want to delete them once deactivated

    function delete_ads(){
    	global $wpdb;
    	$wpdb->query("DROP TABLE ".$wpdb->prefix."video");
    
    }
    register_deactivation_hook(__FILE__,'delete_ads');
    

    Copy and paste this code to your plugin file you will see wp_video table created is gone now. When you deactivate the plugin

    Tip: It is always good to protect direct access to your plugin files. You can do this by adding the following code at the stat of your file i.e before any code or below the header of your main plugin file

    // exit if file is called directly
    if ( ! defined( 'ABSPATH' ) ) {
    	exit;
    }
    

    Plugin Directory Structure

    ( Contains all Plugin files)
    (Same as Main folder Plugin name with .php) Index.php ( A blank index.php file to restrict direct access to files) Licence.txt Readme.txt (Folder All code used by admin ) (Folder all code used by public) ( Any common PHP file)

    This is your basic template for creating a plugin.

    Add Admin Menu:
    With menu item added it is easier for user to find setting and configure the plugin as required.
    You can add two types of admin menu – Top Level Menu or Sub menu. Top level menu has advantage that it can have sub menu. So if your plugin has multiple pages you can go for top level menu else with

    Now let us add a top level menu. Let start by copy and pasting the following code to your main plugin file then I will tell you the meaning of each term one by one.

    // display the plugin settings page
    function explugin_settings_page() {	
    	// check if user is allowed access
    	if ( ! current_user_can( 'manage_options' ) ) return;	
    	?>
    	
    	

    function explugin_register_menu() {
    	/* 
    		add_menu_page(
    			string   $page_title, 
    			string   $menu_title, 
    			string   $capability, 
    			string   $menu_slug, 
    			callable $function = '', 
    			string   $icon_url = '', 
    			int      $position = null 
    		)
    	*/
    	
    	add_menu_page(
    		'Example Plugin Settings',
    		'Example Plugin',
    		'manage_options',
    		'explugin',
    		'explugin_settings_page',
    		'dashicons-admin-generic',
    		null
    	);
    	
    }
    add_action( 'admin_menu', 'explugin_register_menu' );
    
    
    

    Plugin Development

    You can see our top-level menu here. And the settings page
    explugin_register_menu() function adds top-level menu using a function add_menu_page
    Add_menu_page uses various parameters. To make it simple I have added the value for each parameter as a comment.

    • Title of the plugin page.
    • Title of the menu item.
    • Required user capability.
    • Menu slug- a unique string that is used as URL of the plugin page
    • Call back function that will display the plugin page
    • Menu Icon
    • The menu priority. But we will keep it null to avoid conflicts between plugin
      After creating the function we now have to register the plugin with a proper hook. We will use here admin_menu action hook.

    Sub Level Menu. Remove function explugin_register_menu and add following function :

    
    // add sub-level administrative menu
    function explugin_register_sublevel_menu() {
    	
    	/*
    	
    	add_submenu_page(
    		string   $parent_slug,
    		string   $page_title,
    		string   $menu_title,
    		string   $capability,
    		string   $menu_slug,
    		callable $function = ''
    	);
    	
    	*/
    	
    	add_submenu_page(
    		'options-general.php',
    		'explugin Settings',
    		'explugin',
    		'manage_options',
    		'explugin',
    		'explugin_settings_page'
    	);
    	
    }
    add_action( 'admin_menu', 'explugin_register_sublevel_menu' );
    
    

    This sublevel menu is also registered with admin_menu hook. The difference is here we are using add_submenu_page function insted of add_menu_page function.

    Finf parent slug: This defines the top leve menu to which our plugin to be added. If if want our submenu to display under plugins then we use URL as plugins.php
    Tip: Experiment with slug to get a better understainding how that workd
    Here we are displayijg the plugin under settings menu. So we use options_general.php as paramenter.

    Remaingin parameters are almost same as top level menu.

    2) Title#
    3) Name of Menu
    4) Caabiluty
    5) Slug
    6) Callback funtion

    Add Example Plugin.zip file

    WordPress Plugin Development – Part I

Leave a Reply

Your email address will not be published. Required fields are marked *