0
0
WordpressHow-ToBeginner · 4 min read

How to Create a Plugin from Scratch in WordPress

To create a WordPress plugin from scratch, create a new folder in wp-content/plugins and add a PHP file with a plugin header comment. Then write your plugin code inside that file and activate it from the WordPress admin dashboard.
📐

Syntax

A WordPress plugin requires a PHP file with a special header comment that tells WordPress about the plugin. The basic parts are:

  • Plugin Name: The name shown in the admin panel.
  • Description: Short info about what the plugin does.
  • Version: Plugin version number.
  • Author: Your name or company.

After the header, you add your PHP code to add features.

php
<?php
/*
Plugin Name: My First Plugin
Description: A simple plugin example
Version: 1.0
Author: Your Name
*/

// Your plugin code starts here
💻

Example

This example creates a plugin that adds a message at the end of every post content.

php
<?php
/*
Plugin Name: Simple Message Plugin
Description: Adds a message to post content
Version: 1.0
Author: Your Name
*/

function add_custom_message($content) {
    if (is_single() && in_the_loop() && is_main_query()) {
        return $content . '<p><strong>Thank you for reading!</strong></p>';
    }
    return $content;
}
add_filter('the_content', 'add_custom_message');
Output
When viewing a single post, the post content will show the original text plus a bold message: "Thank you for reading!" at the end.
⚠️

Common Pitfalls

Common mistakes when creating WordPress plugins include:

  • Missing the plugin header comment or formatting it incorrectly, so WordPress does not recognize the plugin.
  • Not using WordPress hooks (actions or filters) properly, causing code to not run or break the site.
  • Writing code that runs on every page load without conditions, which can slow down the site.
  • Not sanitizing or escaping output, which can cause security issues.
php
<?php
/*
Plugin Name: Bad Plugin Example
*/

// Wrong: echoing output directly without hooks
// echo 'Hello World';

// Right: Use hooks to add content safely
function good_example() {
    echo 'Hello World';
}
add_action('wp_footer', 'good_example');
📊

Quick Reference

Steps to create a WordPress plugin:

  • Create a folder in wp-content/plugins with your plugin name.
  • Create a main PHP file with the plugin header comment.
  • Add your PHP code using WordPress hooks.
  • Activate the plugin in the WordPress admin panel.

Key Takeaways

Create a PHP file with a proper plugin header inside wp-content/plugins folder.
Use WordPress hooks like actions and filters to add functionality safely.
Always activate your plugin from the WordPress admin dashboard after adding it.
Avoid running code directly without hooks to prevent site issues.
Sanitize and escape data to keep your plugin secure.