Home / WordPress / How to Build a Custom WordPress Plugin from Scratch: A Step-by-Step Guide
devmohsin143

WordPress is the most popular content management system in the world because of its incredible extensibility. While themes control how your website looks, plugins control how it functions. If you want to add custom features without site-wide bloat, learning how to build your own plugin is the ultimate skill. In this comprehensive custom plugin tutorial, we will guide you step-by-step through creating a secure, functional WordPress plugin from scratch.

Whether you want to add a simple shortcode or develop a complex feature, writing custom code in a plugin is far better than editing your theme’s functions.php file. Therefore, when you update or change your theme in the future, your custom functionality will not be lost. Let’s dive into how you can start your plugin development journey today.

Why Create a Custom Plugin Instead of Using functions.php?

Many beginners make the mistake of adding custom snippets to their theme’s functions.php file. However, using a custom plugin is the industry standard for several key reasons:

  • Theme Independence: Your custom features remain fully active even if you switch themes.
  • Better Organization: Keeps your codebase modular, clean, and easier to debug.
  • Performance Control: You can load scripts and styles only where they are needed rather than site-wide.
  • Easy Reusability: You can quickly package and install the same plugin on multiple WordPress websites.

Step 1: Setting Up a Local Development Environment

Before you start writing code, it is essential to have a safe local development environment. Modifying code directly on a live production website can cause downtime. Tools like Local (by WP Engine), DevKinsta, or XAMPP allow you to run WordPress locally on your computer.

Additionally, you will need a reliable code editor to maintain clean syntax. Visual Studio Code, Sublime Text, or PHPStorm are excellent choices for writing clean, error-free PHP and CSS.

Step 2: Creating the Plugin Directory and File

WordPress plugins reside in the /wp-content/plugins/ directory of your installation. To get started, navigate to this folder and create a new directory for your plugin.

For this custom plugin tutorial, we will build a lightweight “Reading Time Calculator” plugin. Let’s name our directory: my-reading-time-calculator.

Inside this folder, create your main PHP file. It is best practice to name this file the exact same as your folder: my-reading-time-calculator.php.

Step 3: Writing the Plugin Header

For WordPress to recognize your file as an active plugin, it must contain a specific header comment block at the very top of the main PHP file. This block tells WordPress the plugin’s name, version, author, description, and license details.

Open your my-reading-time-calculator.php file in your editor and add the following code:

<?php
/**
 * Plugin Name: My Reading Time Calculator
 * Plugin URI: https://wpeducated.com/custom-plugin-tutorial
 * Description: A lightweight custom plugin that calculates and displays the estimated reading time of your posts.
 * Version: 1.0.0
 * Author: WP Educated
 * Author URI: https://wpeducated.com
 * License: GPL2
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: my-reading-time-calculator
 */

// Exit if accessed directly.
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

The code snippet if ( ! defined( 'ABSPATH' ) ) { exit; } is a critical security measure. It prevents anyone from accessing your PHP file directly via their browser, which protects your site from potential remote code execution exploits.

Step 4: Activating Your Custom Plugin

Now that you have created the directory and the main file with the header, log into your WordPress admin dashboard. Navigate to Plugins > Installed Plugins. You should see “My Reading Time Calculator” listed there.

Click the Activate link. Since we have not added any functional logic yet, nothing will change on the front end, but your plugin is now successfully registered and active within WordPress!

Step 5: Writing the Code (Custom Plugin Tutorial Project)

Let’s build a practical feature for our custom plugin tutorial. We will write a function that calculates the reading time of an article based on an average reading speed of 200 words per minute and automatically appends it to the beginning of the post content.

Add the following PHP code below your security check in my-reading-time-calculator.php:

function mrtc_calculate_reading_time( $content ) {
    // Only apply to single posts.
    if ( is_single() && in_the_loop() && is_main_query() ) {
        // Strip tags and shortcodes to get actual text content.
        $clean_content = strip_shortcodes( strip_tags( $content ) );
        
        // Count the words.
        $word_count = str_word_count( $clean_content );
        
        // Calculate minutes (rounding up).
        $reading_time = ceil( $word_count / 200 );
        
        // Create the output message.
        $time_string = '<p class="reading-time-estimate" style="font-style: italic; color: #555;">';
        $time_string .= sprintf( esc_html__( 'Estimated reading time: %d minute(s)', 'my-reading-time-calculator' ), $reading_time );
        $time_string .= '</p>';
        
        // Prepend the reading time to the post content.
        return $time_string . $content;
    }
    
    return $content;
}
add_filter( 'the_content', 'mrtc_calculate_reading_time' );

In this code, we hook into the the_content filter using add_filter(). This allows us to intercept the post content, prepend our custom reading time markup, and return the modified content back to WordPress seamlessly.

Step 6: Custom Plugin Tutorial Security and Best Practices

When writing custom plugins, security should always be your top priority. For more details on standard practices, you can refer to the official WordPress Developer Resources. Meanwhile, here are three major security practices demonstrated in our custom plugin tutorial:

  1. Data Sanitization: Clean any user inputs before processing them (using functions like sanitize_text_field()).
  2. Data Escaping: Always escape output data when rendering HTML to prevent Cross-Site Scripting (XSS) attacks. In our example, we used esc_html__() to ensure safe internationalized translation strings.
  3. Prefixing Everything: To prevent conflicts with other plugins or themes, prefix all your functions, classes, and global variables. In our plugin, we prefixed our function with mrtc_ (My Reading Time Calculator).

Step 7: Structuring Larger Plugins

As your custom plugins grow, keeping all code in a single file will become unmanageable. Therefore, it is best practice to organize your codebase into a clean, predictable directory structure:

Directory / FileDescription
/admin/Contains admin-specific PHP, CSS, and JS files for dashboard settings.
/public/Contains CSS, JS, and PHP files for frontend rendering.
/includes/Contains core logic files, helper functions, and class definitions.
my-reading-time-calculator.phpThe main loader file that bootstraps your custom plugin.

Conclusion and Next Steps

Congratulations! You have successfully built your very first functional WordPress plugin. By following this custom plugin tutorial, you learned how WordPress reads plugin metadata, how hooks (filters and actions) work, and how to write secure, clean code that keeps your site optimized.

From here, you can expand your skills by adding an admin options page so users can change the words-per-minute rate directly from the dashboard, or even bundle styles using custom CSS files. To dive deeper into advanced WordPress automation and administration, consider reviewing our WP-CLI Beginner’s Guide.

Related Blogs

Learn how to improve WordPress website speed safely. Actionable guide covering image optimization, caching, database cleanup, and hosting without breaking your site.
Confused by speed test scores? Learn how to accurately interpret website speed test results, analyze Core Web Vitals like LCP, INP, CLS, and TTFB, and fix bottlenecks efficiently.
Master the exact workflow for testing WordPress website speed. Learn how to use PageSpeed Insights, GTmetrix, and Core Web Vitals to accurately diagnose performance bottlenecks.