How do you write a custom plugin from scratch?

1. Plan the Plugin

  • Decide what the plugin will do (feature/functionality).
  • Name it uniquely to avoid conflicts.

2. Create the Plugin Folder & File

  1. Go to: bashCopyEdit/wp-content/plugins/
  2. Create a folder: perlCopyEditmy-custom-plugin
  3. Inside, create a PHP file: perlCopyEditmy-custom-plugin.php

3. Add the Plugin Header

This tells WordPress your file is a plugin:

<?php
/*
Plugin Name: My Custom Plugin
Plugin URI: https://example.com
Description: A simple plugin that does something useful.
Version: 1.0
Author: Your Name
Author URI: https://example.com
License: GPL2
*/

4. Write the Plugin Code

Example: Add a custom message at the end of every post.

function mcp_add_footer_message( $content ) {
    if ( is_single() ) {
        $content .= '<p style="color: blue;">Thank you for reading!</p>';
    }
    return $content;
}
add_filter( 'the_content', 'mcp_add_footer_message' );

5. Activate the Plugin

  • Go to WordPress Admin β†’ Plugins.
  • Find My Custom Plugin.
  • Click Activate.

6. Best Practices

  • Prefix all function names to avoid conflicts (mcp_ in example).
  • Use hooks (add_action, add_filter) instead of modifying core files.
  • Sanitize and validate all user input.
  • Escape all output (esc_html(), esc_attr()).
  • Add uninstall.php for cleanup when plugin is deleted.

7. Optional: Add More Files

  • includes/ folder for organizing large plugins.
  • assets/css/ and assets/js/ for styling and scripts.
  • readme.txt for WordPress.org submission.

πŸ’‘ Analogy:
Creating a plugin is like adding a new appliance to your kitchen β€” it’s separate from the main house (WordPress core), can be plugged in or unplugged anytime, and gives you extra functionality without altering the structure.

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *