Table of Contents
Overview
What is a WordPress Plugin?
A WordPress plugin is a piece of software, written in PHP language, that extends or enhances the functionality of a WordPress website. By using the proper WordPress APIs, plugins allow you to add new features or modify existing features on your site without altering the core WordPress files.
Folder and File Structure
Why Folder and File Structure is important?
Basically, we can put everything in one file and it starts functioning, but we should create a folder and file structure for organization, readability, and ease of maintenance. Separating code into multiple files allows for easier debugging, updates, and collaboration. It also ensures that different components, like logic, styles, and scripts, are modular and manageable. This structure makes the plugin scalable and more efficient to work with over time.
Basic Folder and File Structure
/wp-content/plugins/
|---/simple-plugin/
| |---simple-plugin.php
| |---/includes/
| |---/assets/
| | |---/css/
| | |---/js/
| | |---/images/
| |---/languages/
| |---/templates/
| |---uninstall.php
Plugin Directory (/simple-plugin/):
This is the main folder for your plugin. It should have a unique name, ideally matching your plugin’s name in a slug format (notice the name of the main plugin file that matches the name of the plugin folder). All your plugin files and subdirectories will reside here.
Main Plugin File (simple-plugin.php):
This file is the entry point of your plugin. It also contains the plugin’s header information, which WordPress uses to identify and display the plugin in the admin dashboard. More details in this regard are provided in the next sections.
/includes/ Directory:
This directory is used to store any PHP files that contain additional functionality for your plugin. This might include functions, classes, or helper files that can be included in the main file.
/assets/ Directory:
This folder holds your plugin’s static assets, such as stylesheets, JavaScript files, images, and even fonts.
/languages/ Directory:
If your plugin supports multiple languages, you’ll place the translation files in this directory. These files usually have a .mo and .po extension.
Example: simple-plugin-en_US.mo, simple-plugin-en_US.po
/templates/ Directory:
This is the place where you store template files that are responsible for generating HTML output. These templates define the structure and layout of the content that your plugin displays on the front end of the website.
uninstall.php File:
This file is optional but recommended. It contains the code to clean up after your plugin if a user decides to uninstall it. This might include deleting custom database tables or options created by your plugin.
Example content:
if (!defined('WP_UNINSTALL_PLUGIN')) {
die;
}
// Clean up database entries
delete_option('simple_plugin_option');
Main Plugin File
Plugin Header Information
In the main plugin file (simple-plugin.php) we must write the plugin’s header information as a comment block at the beginning of the file (after <?php tag), which WordPress uses to identify and display the plugin in the admin dashboard.
Example content:
/*
Plugin Name: Simple Plugin
Plugin URI: https://example.com/
Description: A simple plugin for demonstration.
Version: 1.0
Author: Your Name
Author URI: https://yourwebsite.com/
License: GPL2
Domain Path: /languages
*/
Plugin Name: This is the name of your plugin as it will appear in the WordPress admin dashboard under the “Plugins” section.
Plugin URI: This is the URL of the plugin’s homepage or documentation page. It could be a page on your website where users can find more information about the plugin.
Description: A brief description of what your plugin does. This will be displayed in the plugin list in the WordPress admin area.
Version: The version number of your plugin. This helps users and developers track changes and updates.
Author: The name of the person or organization that created the plugin.
Author URI: The URL to the author’s personal website or profile page.
License: Specifies the license under which the plugin is distributed. WordPress plugins are typically licensed under the GNU General Public License (GPL), version 2 or later. This is important for legal reasons and ensures that the plugin complies with WordPress’s open-source philosophy.
Domain Path: Specifies the directory where your plugin’s translation files (.mo and .po files) are located.
More info about header requirements: https://developer.wordpress.org/plugins/plugin-basics/header-requirements/
After adding your plugin to WordPress, it should now appear in the “plugins” section in the admin dashboard:
By activating the plugin, the main plugin file (the file containing the header information comment) will be loaded and the codes will function alongside the WordPress core codes as an extension, and by deactivating the plugin, the codes will be unloaded.
You can manage the activated/deactivated WordPress plugins in the database Inside the “wp_options” table.
Define Path & URL Constants
In WordPress plugin development, managing file paths and URLs correctly is crucial for ensuring that your plugin’s assets (like CSS, JavaScript, images, and other files) are loaded properly, regardless of the site's configuration. Two important functions provided by WordPress for this purpose are
plugin_dir_path()andplugin_dir_url(). You can use them like:
define('SIMPLE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('SIMPLE_PLUGIN_URL', plugin_dir_url(__FILE__));
The
__FILE__variable is a PHP magic constant that returns the full path of the file in which it is used. Now we can use the defined constants anywhere that requires the path or the URL of the included files. For example, if we want to include sample_file.php from the includes directory, we can simply write:
Include SIMPLE_PLUGIN_DIR . “includes/sample_file.php”;
Hooks
Action Hooks
An action hook is a specific point in the WordPress codebase where developers can "hook" into the code to execute their own functions. When WordPress reaches an action hook, it adds any custom functions that have been attached to that hook using the
add_action()function, and then the custom functions can now be executed using thedo_action()function.
Example code:
function print_order_id()
{
print "order purchased!";
}
function send_order_email()
{
print "Order email sent";
}
function send_order_sms()
{
print "Order sms sent";
}
add_action('user_purchase_order', 'print_order_id');
add_action('user_purchase_order', 'send_order_email');
add_action('user_purchase_order', 'send_order_sms');
do_action('user_purchase_order');
The
user_purchase_orderis the tag we define for the group of our custom functions.
Filter Hooks
Unlike action hooks, which are used to execute custom code at specific points in the WordPress execution process, filter hooks are specifically designed to manipulate and return data. By using
add_filter()andapply_filter(), you can attach a custom function to a filter hook, and apply the filters on them, which returns the filtered data.
Example code:
function update_order_price($order_price)
{
return $order_price * 2;
}
function update_order_price2($order_price)
{
return $order_price / 5;
}
function update_order_price3($order_price)
{
return $order_price + 3000;
}
add_filter('get_order_price','update_order_price');
add_filter('get_order_price','update_order_price2');
add_filter('get_order_price','update_order_price3');
$result = apply_filters('get_order_price', 25000);
print $result;
Note that filter functions must return a value.
Activation Hooks
Activation hooks in WordPress are a special type of action hook that runs when a plugin is activated or deactivated. They are used to perform setup tasks that your plugin requires to function correctly, such as creating database tables, setting default options, etc.
Example code:
function simple_plugin_activation()
{
// operation
}
function simple_plugin_deactivation()
{
// operation
}
register_activation_hook(__FILE__, 'simple_plugin_activation');
register_deactivation_hook(__FILE__, 'simple_plugin_deactivation');
Shortcode Hooks
Shortcodes in WordPress are a powerful way to embed dynamic content within posts, pages, or widgets without writing HTML or PHP code directly in the content editor. Shortcode hooks refer to the process of registering and using shortcodes in your plugin or theme.
A shortcode is a small piece of code enclosed in square brackets [] that you can place in the content of a post, page, or widget to dynamically display content or execute functions. Shortcodes are often used to embed custom forms, galleries, sliders, and other elements without requiring users to write code.
By using theadd_shortcode()function you can register the shortcode and benefit from its feature.
Example code:
function ajax_form()
{
include SIMPLE_PLUGIN_DIR . 'templates/form.php';
}
add_shortcode('wp_ajax_form', 'ajax_form');
Now, the
[wp_ajax_form]shortcode is available to be used in WordPress pages, which loads all the HTML or PHP code we included in our custom function.
Separate admin and front-end functions for WordPress plugins
Separating admin and front-end functions in a WordPress plugin or theme is an effective way to ensure that specific code is only executed in the appropriate context either in the WordPress admin dashboard or on the front end of the site. For this purpose, we use the
is_admin()function which is provided by WordPress, and checks if the current request is being made within the admin area or not.
Example code:
if (is_admin()) {
// Admin dashboard codes
include SIMPLE_PLUGIN_DIR . 'includes/admin/menus.php';
} else {
// Front-end codes
include SIMPLE_PLUGIN_DIR. 'includes/user/menus.php';
}
Note that
is_admin()refers to the context, not the user role.
Share this article: