How to Create a Custom WordPress Plugin from Scratch

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.

What Makes a WordPress Plugin?

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 — my-first-plugin.php
<?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.

Plugin Structure Best Practices

While a single file works for simple plugins, organise complex plugins as a directory:

Directory Structure
/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.

01
The Main Plugin File

Create /wp-content/plugins/my-first-plugin/my-first-plugin.php:

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.
02
Understanding WordPress Hooks

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

Actions let you run code at specific points in WordPress's execution. You "hook in" to a specific action with add_action().

PHP — Action Hook
// 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:

ActionWhen It RunsUse For
initAfter WordPress loads, before headersRegistering post types, taxonomies
admin_initIn admin onlyAdmin-specific setup
wp_enqueue_scriptsFront-end script enqueueingLoading CSS and JS
admin_enqueue_scriptsAdmin script enqueueingLoading admin CSS and JS
save_postWhen a post is savedPost save operations
wp_footerJust before </body>Adding footer content

Filters

Filters let you modify data before it's used or displayed. You return the modified value.

PHP — Filter Hook
// 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
}
Critical: Always return in filter callbacks. If you forget to return, the filtered value becomes null, breaking the page.

Common filters:

FilterWhat It Modifies
the_contentPost content before display
the_titlePost title
excerpt_lengthNumber of words in auto-generated excerpts
upload_mimesAllowed file upload types
wp_mailEmail data before sending
03
Creating a Shortcode

Shortcodes let users embed plugin output anywhere — posts, pages, widgets — using [my_shortcode] syntax.

PHP — Shortcode
// 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:

Shortcode
[my_notice type="success" title="Done!"]Your form was submitted.[/my_notice]
Critical: Shortcode callbacks must 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.
Security: sanitize_text_field() and esc_html() are data security functions — always sanitise input and escape output.
04
Enqueueing Scripts and Styles

Never use raw <script> or <link> tags in plugins. Use WordPress's enqueue system:

PHP — Asset Enqueueing
// 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:

  • Prevents loading the same file twice (dependency management)
  • Handles load order through the dependency system
  • Allows other plugins to dequeue your scripts if needed
  • Works correctly with caching plugins
05
Creating an Admin Page

Add a settings page to the WordPress admin:

PHP — Admin Menu Page
// 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:

PHP — Settings Registration
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
}
06
Activation, Deactivation, and Uninstall Hooks

Run code when your plugin is activated, deactivated, or deleted:

PHP — Lifecycle Hooks
// 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 — 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" );
Tip: The uninstall.php approach (versus register_uninstall_hook) is cleaner and runs even if the plugin is not active when deleted.
07
Interacting with the Database

For complex data that doesn't fit WordPress's native options or post meta systems, create a custom database table:

PHP — Create 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:

PHP — Insert Data
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:

PHP — Query Data
$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
    )
);
Security: Always use $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.

WordPress Plugin Security Checklist

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

Nonce Verification Example

PHP — Nonce in Form & Handler
// 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' );
}

Sanitise & Escape Reference

Function Used For When
sanitize_text_field()Plain text inputSanitising input
sanitize_email()Email addressesSanitising input
absint()Positive integersSanitising input
wp_kses_post()Content with allowed HTMLSanitising input
esc_html()HTML content in outputEscaping output
esc_attr()HTML attribute valuesEscaping output
esc_url()URLs in outputEscaping output

Plugin Anatomy: Quick Reference

Component Function WordPress API
Plugin HeaderTells WordPress the plugin existsComment block at top of main file
Action HooksRun code at specific execution pointsadd_action()
Filter HooksModify data before use/displayadd_filter()
ShortcodesEmbed output in post/page contentadd_shortcode()
Asset EnqueueingLoad CSS and JS properlywp_enqueue_style(), wp_enqueue_script()
Admin PagesAdd settings pages to wp-adminadd_menu_page(), Settings API
Activation/DeactivationSetup and cleanup on state changeregister_activation_hook()
UninstallRemove all plugin data on deletionuninstall.php
DatabaseCustom tables for complex data$wpdb, dbDelta()

Frequently Asked Questions

Q: Should I use a plugin boilerplate?
A: For serious plugin development, the WordPress Plugin Boilerplate provides a well-structured starting point following WordPress coding standards. For learning, building from scratch first is valuable before introducing the boilerplate's abstractions.
Q: Can plugins conflict with each other?
A: Yes — primarily through function name collisions (solved by consistent prefixing and namespacing), hook priority conflicts, and JavaScript library conflicts. Following WordPress coding standards minimises these risks.
Q: Should I use OOP or procedural code for plugins?
A: Modern WordPress development favours object-oriented PHP for plugins of any complexity — it handles namespacing, prevents global function conflicts, and is more maintainable. Simple plugins can use procedural code. As plugin complexity grows, OOP becomes clearly preferable.
Q: What's the difference between add_action and add_filter?
A: 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.
Q: How do I debug my plugin during development?
A: Enable 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.
Q: Can I sell my plugin commercially?
A: Yes. While WordPress itself is GPL-licensed (requiring your plugin to also be GPL if it uses WordPress functions), you can sell GPL-licensed software — the licence allows commercial distribution. Many successful plugin companies (Gravity Forms, Yoast, ACF) do exactly this.

Final Thoughts

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.
Views: 64