sitespecificplugin

Create a Simple Plugin in WordPress – 1 – Create a plugin files

In this lesson, We will create a simple plugin files in WP, configure security rules, Initiate 3 hooks (Activation hook, Deactivation hook & Uninstall hook) & Create a short-code of this plugin.

You can review official document of plugin basics here.

You can create all custom plugin basic files & structure by ready made tool like plugin boiler plate https://wppb.me/

But I suggest to not use it if you want to learn it. Just review it for comparison purpose.

part-1Security measurements

First we have to create plugin directory in wp-content/plugins folder. In that plugin file add a blank index.php so no one can access plugin files using directory URL.

Also define plugin’s basic information in comments at top of the plugin file.

<?php 
/*
    Plugin Name: Test plugin
    Description: This is a test plugin developed by DILIP
    Version: 1.0.0
    Author: DILIP PARMAR
    Author URI: https://dilip-parmar.in
*/

Now anyone can access the plugin directory using URL like: http://localhost/wordpress-6.3.2/wp-content/plugins/testplugin/testplugin.php We should protect them to access this file using URL so we have to use below code as first part of the plugin file.

Also please note we are not going to echo anything in plugin files directly. All echo statements are in proper functions only.

if (!defined('ABSPATH')) {
    header('Location: /');
    die();
}

What is ABSPATH and Where it defined? — If you go to WordPress root index.php file you can see one file is imported: wp-blog-header.php That file is loads wp-load.php & that wp-load.php file already has below code:

if ( ! defined( 'ABSPATH' ) ) {
	define( 'ABSPATH', __DIR__ . '/' );
}

THAT MEANS ABSPATH IS ALREADY DEFILED IF SOMEONE TRY TO ACCESS VIA WORDPRESS DIRECTORY SYSTEM. So we added that if ABSPATH is not defined that means not a proper way to access the plugin file so we denied it and redirected to home again.

Part – 2: Calling 3 hooks

We can defined functions and call them on particular events like activation, deactivation & un-installation of plugin.

// Calling 3 hooks 
function testplugin_activation()
{
}
register_activation_hook(__FILE__, 'testplugin_activation');

function testplugin_deactivation()
{
}
register_deactivation_hook(__FILE__, 'testplugin_deactivation');

To uninstall we need to create a separate file as uninstall.php and add some code to protect again direct run through URL.

<?php
// if uninstall.php is not called by WordPress, die
if (!defined('WP_UNINSTALL_PLUGIN')) {
    die;
}

Part – 3: Creating a short-code

Just to create a short-code by below code and you can use short code like: [test-plugin] anywhere on same site.

function callback_shortcode()
{
    return '<h1>This is a plugin short-code</h1>';
}
add_shortcode('test-plugin', 'callback_shortcode');

That’s it for this lesson.