How to create a WordPress plugin
7 July 2024 (Updated 8 July 2024)
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:
Use actions and filters to do things with your plugin
You can use WordPress’s actions and filters to make your plugin do things.
- Actions let you add or change WordPress functionality.
- Filters let you alter content as it’s loaded or displayed on the website.
There are three basic hooks you’ll typically use when creating a plugin:
- register_activation_hook(): Lets you run code when your plugin is activated by the WP admin user (e.g., add custom database tables or set default option values).
- register_deactivation_hook(): Lets you run code when your plugin is deactivated (e.g., remove temporal data like cache or temporary files).
- register_uninstall_hook() : Lets you run code when your plugin is uninstalled (e.g., remove records from the
options
table.
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
Tagged:
WordPress
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment