sajad torkamani

Create a basic plugin

At its simplest, a WordPress plugin is just a PHP file with a WordPress plugin header comment.

Here’s how to create a basic first plugin:

cd wp-content/plugins
mkdir hello-world && cd hello-world
vim hello-world.php

Write a basic plugin header comment:

<?php
/*
* Plugin Name:       My Basics Plugin
* Plugin URI:        https://example.com/plugins/the-basics/
* Description:       A simple WordPress plugin.
* Version:           0.0.1
* Requires PHP:      8.3.4
* Author:            John Smith
* Author URI:        https://author.example.com/
* License:           GPL v2 or later
*/

Now, your plugin should be listed on the plugins page:

How to create a WordPress plugin

Use actions and filters to do things with your plugin

You can use WordPress’s actions and filters to make your plugin do things.

There are three basic hooks you’ll typically use when creating a plugin:

Here’s an example plugin that does various things on being activated, deactivated, and uninstalled:

<?php
/*
* Plugin Name:       Hello World
* Plugin URI:        https://example.com/plugins/the-basics/
* Description:       A simple WordPress plugin.
* Version:           0.0.1
* Requires PHP:      8.3.4
* Author:            John Smith
* Author URI:        https://author.example.com/
* License:           GPL v2 or later
*/

// This function is called when the plugin is activated.
// Note: Using a prefix like `sthw` that identifies your plugin 
// (e.g., 'Sajad Torkamani Hello Word') for functions/classes is 
// considered a best practice for WordPress plugins to avoid 
// conflicts with other plugins.
function sthw_activate(): void
{
  sthw_create_file('hello_word_activated');
}

// This function is called when the plugin is deactivated.
function sthw_deactivate(): void
{
  sthw_create_file('hello_word_deactivated');
}

// This function is called when the plugin is uninstalled.
function sthw_uninstalled(): void
{
  sthw_create_file('hello_word_uninstalled');
}

function sthw_timestamp(): string
{
  return date('d-m-Y_h-i-s');
}

function sthw_create_file(string $filename): void
{
  $dir = ABSPATH . 'tmp/hello-world';
  
  if (!is_dir($dir)) {
    mkdir($dir, 0755, true);
  }
  
  touch("$dir/" . $filename . '_' . sthw_timestamp() . '.txt');
}

register_activation_hook(__FILE__, 'sthw_activate');
register_deactivation_hook(__FILE__, 'sthw_deactivate');
register_uninstall_hook(__FILE__, 'sthw_uninstall');

Links