Every WordPress plugin starts with the same thing: a PHP file with a comment block that tells WordPress it exists. From that humble beginning, you can build anything — new post types, custom admin pages, API integrations, database tables, front-end components, and sophisticated business logic.
Understanding plugin development unlocks a fundamental WordPress skill: the ability to add any behaviour to WordPress without modifying core files, knowing that your code will survive every future WordPress update.
This guide builds a real plugin from scratch — progressively adding functionality to illustrate the core concepts every plugin developer needs.
A WordPress plugin is a PHP file (or a directory containing PHP files) placed in /wp-content/plugins/. The only requirement for WordPress to recognise a file as a plugin is a specific comment block at the top called the plugin header.
Here's the minimal viable plugin header:
<?php
/**
* Plugin Name: My First Plugin
* Description: A plugin that demonstrates the basics of WordPress plugin development.
* Version: 1.0.0
* Author: AceMindTech
* Author URI: https://acemindtech.com
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: my-first-plugin
*/
That's it. Create a file called my-first-plugin.php in /wp-content/plugins/my-first-plugin/, add this header, and WordPress will show "My First Plugin" in the Plugins list ready to activate.
While a single file works for simple plugins, organise complex plugins as a directory:
/wp-content/plugins/my-first-plugin/
my-first-plugin.php (main plugin file with header)
includes/
class-admin.php (admin functionality)
class-frontend.php (front-end functionality)
admin/
css/
js/
partials/
public/
css/
js/
languages/ (translation files)
README.txt
This structure separates concerns, makes testing easier, and is consistent with how the WordPress Plugin Boilerplate (a community-maintained starting template) organises code.
Create /wp-content/plugins/my-first-plugin/my-first-plugin.php:
<?php
/**
* Plugin Name: My First Plugin
* Description: Demonstrates WordPress plugin development fundamentals.
* Version: 1.0.0
* Author: AceMindTech
* Author URI: https://acemindtech.com
* License: GPL v2 or later
* Text Domain: my-first-plugin
*/
// Prevent direct file access
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
// Define plugin constants
define( 'MFP_VERSION', '1.0.0' );
define( 'MFP_PLUGIN_DIR', plugin_dir_path( __FILE__ ) );
define( 'MFP_PLUGIN_URL', plugin_dir_url( __FILE__ ) );
// Include dependencies
require_once MFP_PLUGIN_DIR . 'includes/class-admin.php';
require_once MFP_PLUGIN_DIR . 'includes/class-frontend.php';
// Initialise the plugin
function mfp_init() {
$admin = new MFP_Admin();
$frontend = new MFP_Frontend();
}
add_action( 'plugins_loaded', 'mfp_init' );
Key concepts introduced:
if ( ! defined( 'ABSPATH' ) ) { exit; } — Security check. ABSPATH is defined by WordPress. If the file is accessed directly (not through WordPress), the script exits immediately.plugin_dir_path( __FILE__ ) — Returns the absolute filesystem path to the plugin's directory.plugin_dir_url( __FILE__ ) — Returns the URL to the plugin's directory (for enqueueing assets).add_action( 'plugins_loaded', 'mfp_init' ) — Hooks the initialisation function to run after all plugins are loaded.Hooks are the foundation of plugin development. Without them, you'd have to modify WordPress core files to change behaviour — destroying update-ability. There are two types:
Actions let you run code at specific points in WordPress's execution. You "hook in" to a specific action with add_action().
// Syntax: add_action( 'hook_name', 'function_to_run', $priority, $accepted_args );
add_action( 'wp_footer', 'mfp_add_footer_text' );
function mfp_add_footer_text() {
echo '<p>Powered by My First Plugin</p>';
}
Common actions:
| Action | When It Runs | Use For |
|---|---|---|
init | After WordPress loads, before headers | Registering post types, taxonomies |
admin_init | In admin only | Admin-specific setup |
wp_enqueue_scripts | Front-end script enqueueing | Loading CSS and JS |
admin_enqueue_scripts | Admin script enqueueing | Loading admin CSS and JS |
save_post | When a post is saved | Post save operations |
wp_footer | Just before </body> | Adding footer content |
Filters let you modify data before it's used or displayed. You return the modified value.
// Syntax: add_filter( 'hook_name', 'function_to_run', $priority, $accepted_args );
add_filter( 'the_content', 'mfp_append_to_content' );
function mfp_append_to_content( $content ) {
if ( is_single() ) {
$content .= '<div class="share-prompt">Did you find this useful? Share it!</div>';
}
return $content; // Always return the (modified) content
}
return in filter callbacks. If you forget to return, the filtered value becomes null, breaking the page.Common filters:
| Filter | What It Modifies |
|---|---|
the_content | Post content before display |
the_title | Post title |
excerpt_length | Number of words in auto-generated excerpts |
upload_mimes | Allowed file upload types |
wp_mail | Email data before sending |
Shortcodes let users embed plugin output anywhere — posts, pages, widgets — using [my_shortcode] syntax.
// Register the shortcode
add_shortcode( 'my_notice', 'mfp_render_notice' );
function mfp_render_notice( $atts, $content = null ) {
// Parse attributes with defaults
$atts = shortcode_atts(
array(
'type' => 'info', // info, success, warning, error
'title' => 'Notice',
),
$atts,
'my_notice'
);
$type = sanitize_text_field( $atts['type'] );
$title = sanitize_text_field( $atts['title'] );
ob_start(); // Start output buffering
?>
<div class="mfp-notice mfp-notice-<?php echo esc_attr( $type ); ?>">
<strong><?php echo esc_html( $title ); ?></strong>
<?php if ( $content ) : ?>
<p><?php echo esc_html( $content ); ?></p>
<?php endif; ?>
</div>
<?php
return ob_get_clean(); // Return buffered output (don't echo!)
}
Usage in a post:
[my_notice type="success" title="Done!"]Your form was submitted.[/my_notice]
return output, never echo. Echoing inside a shortcode causes the output to appear in the wrong position on the page (usually at the top). Use ob_start() and ob_get_clean() to capture output and return it.sanitize_text_field() and esc_html() are data security functions — always sanitise input and escape output.Never use raw <script> or <link> tags in plugins. Use WordPress's enqueue system:
// Enqueue front-end assets
add_action( 'wp_enqueue_scripts', 'mfp_enqueue_assets' );
function mfp_enqueue_assets() {
wp_enqueue_style(
'mfp-style', // Handle (unique identifier)
MFP_PLUGIN_URL . 'public/css/mfp-public.css',
array(), // Dependencies
MFP_VERSION // Version (for cache busting)
);
wp_enqueue_script(
'mfp-script',
MFP_PLUGIN_URL . 'public/js/mfp-public.js',
array( 'jquery' ), // Depends on jQuery
MFP_VERSION,
true // Load in footer (not <head>)
);
// Pass PHP data to JavaScript
wp_localize_script(
'mfp-script',
'mfpData', // JavaScript variable name
array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'mfp_nonce' ),
)
);
}
The enqueue system:
Add a settings page to the WordPress admin:
// Add menu item and page
add_action( 'admin_menu', 'mfp_add_admin_menu' );
function mfp_add_admin_menu() {
add_menu_page(
'My First Plugin Settings', // Page title
'My Plugin', // Menu title
'manage_options', // Required capability
'my-first-plugin', // Menu slug
'mfp_render_settings_page', // Callback function
'dashicons-smiley', // Icon (Dashicons class)
80 // Menu position
);
}
function mfp_render_settings_page() {
// Check user has permission
if ( ! current_user_can( 'manage_options' ) ) {
return;
}
?>
<div class="wrap">
<h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
<form method="post" action="options.php">
<?php
settings_fields( 'mfp_settings_group' );
do_settings_sections( 'my-first-plugin' );
submit_button( 'Save Settings' );
?>
</form>
</div>
<?php
}
Registering Settings with the Settings API:
add_action( 'admin_init', 'mfp_register_settings' );
function mfp_register_settings() {
// Register a setting
register_setting(
'mfp_settings_group', // Option group
'mfp_option_name', // Option name
array(
'type' => 'string',
'sanitize_callback' => 'sanitize_text_field',
'default' => '',
)
);
// Add a settings section
add_settings_section(
'mfp_general_section',
'General Settings',
'mfp_section_description_callback',
'my-first-plugin'
);
// Add a field to the section
add_settings_field(
'mfp_option_name',
'My Option',
'mfp_option_field_callback',
'my-first-plugin',
'mfp_general_section'
);
}
function mfp_section_description_callback() {
echo '<p>Configure your plugin settings below.</p>';
}
function mfp_option_field_callback() {
$value = get_option( 'mfp_option_name', '' );
?>
<input type="text"
name="mfp_option_name"
value="<?php echo esc_attr( $value ); ?>"
class="regular-text">
<?php
}
Run code when your plugin is activated, deactivated, or deleted:
// Activation hook — runs when plugin is activated
register_activation_hook( __FILE__, 'mfp_activate' );
function mfp_activate() {
// Create custom database tables
mfp_create_tables();
// Set default options
add_option( 'mfp_option_name', 'default_value' );
// Flush rewrite rules if registering custom post types
flush_rewrite_rules();
}
// Deactivation hook — runs when plugin is deactivated
register_deactivation_hook( __FILE__, 'mfp_deactivate' );
function mfp_deactivate() {
// Clear scheduled events
wp_clear_scheduled_hook( 'mfp_scheduled_event' );
// Flush rewrite rules
flush_rewrite_rules();
}
// Uninstall — create uninstall.php in plugin directory
// WordPress calls this when plugin is deleted from admin
Create /wp-content/plugins/my-first-plugin/uninstall.php:
<?php
// Only run if WordPress triggered this
if ( ! defined( 'WP_UNINSTALL_PLUGIN' ) ) {
exit;
}
// Clean up all plugin data
delete_option( 'mfp_option_name' );
// Drop custom tables if you created any
global $wpdb;
$wpdb->query( "DROP TABLE IF EXISTS {$wpdb->prefix}my_plugin_table" );
uninstall.php approach (versus register_uninstall_hook) is cleaner and runs even if the plugin is not active when deleted.For complex data that doesn't fit WordPress's native options or post meta systems, create a custom database table:
function mfp_create_tables() {
global $wpdb;
$table_name = $wpdb->prefix . 'my_plugin_data';
$charset_collate = $wpdb->get_charset_collate();
$sql = "CREATE TABLE $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
user_id bigint(20) NOT NULL,
data_value text NOT NULL,
created_at datetime DEFAULT CURRENT_TIMESTAMP NOT NULL,
PRIMARY KEY (id),
KEY user_id (user_id)
) $charset_collate;";
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
dbDelta( $sql );
}
Inserting data safely:
global $wpdb;
$table_name = $wpdb->prefix . 'my_plugin_data';
$wpdb->insert(
$table_name,
array(
'user_id' => get_current_user_id(),
'data_value' => sanitize_text_field( $input_data ),
),
array( '%d', '%s' ) // Format specifiers (%d = integer, %s = string)
);
Querying data safely using prepared statements:
$user_id = get_current_user_id();
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT * FROM {$wpdb->prefix}my_plugin_data WHERE user_id = %d",
$user_id
)
);
$wpdb->prepare() to prevent SQL injection. Never concatenate user input directly into SQL queries. Use dbDelta() for table creation — it creates or updates tables safely.Every plugin should implement these security practices:
| Practice | Code Example | Prevents |
|---|---|---|
| Check user capabilities | current_user_can( 'manage_options' ) |
Unauthorised actions |
| Verify nonces | wp_verify_nonce( $_POST['mfp_nonce'], 'mfp_save_data' ) |
CSRF attacks |
| Sanitise input | sanitize_text_field(), sanitize_email(), absint() |
Malicious data entry |
| Escape output | esc_html(), esc_attr(), esc_url() |
XSS attacks |
| Prevent direct access | if ( ! defined( 'ABSPATH' ) ) { exit; } |
Direct file execution |
| Use prepared statements | $wpdb->prepare() |
SQL injection |
| Prefix everything | mfp_ prefix on all functions, classes, options |
Name collisions |
// In form output:
wp_nonce_field( 'mfp_save_data', 'mfp_nonce' );
// In form handler:
if ( ! wp_verify_nonce( $_POST['mfp_nonce'], 'mfp_save_data' ) ) {
wp_die( 'Security check failed' );
}
| Function | Used For | When |
|---|---|---|
sanitize_text_field() | Plain text input | Sanitising input |
sanitize_email() | Email addresses | Sanitising input |
absint() | Positive integers | Sanitising input |
wp_kses_post() | Content with allowed HTML | Sanitising input |
esc_html() | HTML content in output | Escaping output |
esc_attr() | HTML attribute values | Escaping output |
esc_url() | URLs in output | Escaping output |
| Component | Function | WordPress API |
|---|---|---|
| Plugin Header | Tells WordPress the plugin exists | Comment block at top of main file |
| Action Hooks | Run code at specific execution points | add_action() |
| Filter Hooks | Modify data before use/display | add_filter() |
| Shortcodes | Embed output in post/page content | add_shortcode() |
| Asset Enqueueing | Load CSS and JS properly | wp_enqueue_style(), wp_enqueue_script() |
| Admin Pages | Add settings pages to wp-admin | add_menu_page(), Settings API |
| Activation/Deactivation | Setup and cleanup on state change | register_activation_hook() |
| Uninstall | Remove all plugin data on deletion | uninstall.php |
| Database | Custom tables for complex data | $wpdb, dbDelta() |
add_action() runs code at a specific point (like inserting content into a footer) — you don't return anything. add_filter() modifies data that WordPress is about to use (like changing post content before display) — you must return the modified value. Both use the same hook system but serve different purposes.
WP_DEBUG and WP_DEBUG_LOG in wp-config.php. Use error_log() to write to /wp-content/debug.log. For front-end JavaScript, use browser developer tools. The Query Monitor plugin is invaluable for debugging database queries, hooks, and PHP errors.
Building a WordPress plugin is fundamentally about using hooks to extend WordPress without modifying core. Everything else — settings pages, shortcodes, custom tables, asset enqueueing — follows from that foundational principle.
Start simple: a plugin file, one action hook, one filter. Add complexity incrementally. Follow security practices from the first line of code. And prefix everything.
The WordPress developer community has extensive documentation at developer.wordpress.org — the best comprehensive reference for plugin development.
Need a custom WordPress plugin built for your business? Our development team builds secure, well-architected plugins tailored to your exact requirements.
Contact us today and we'll sort it out.