phprockers-logo

wordpress

How to Create a Simple WordPress Plugin

Creating a plugin in WordPress is easier than you might think. There are currently over 8,500 plugins in the wordpress.org repository (not including paid plugins), so that should say something.

For starters, WordPress has a fairly extensive plugin API system, granting you the ability to hook into various parts of WordPress without needing to touch the core code directly.

WordPress comes with two kinds of hooks: actions and filters. Actions allow you to run PHP functions at a certain point of execution (such as when the header has loaded or when a post has been submitted). Filters also allow you to run PHP functions — modifying data passing through them — before either being outputted or saved to the database.

In the following example, I've created a simple plugin to email a specified user whenever a new post has been published:

<?php
/*
Plugin Name: my_own
Description: Notify a user once a post has been published.
Author: Ramakrishnan V
Version: 1.0.0
*/

add_action('admin_menu', 'my_plugin_menu');

function my_plugin_menu() {
        add_options_page('My Plugin Options', 'My Plugin', 'manage_options', 'my-unique-identifier', 'my_plugin_options');
}

function my_plugin_options() {
        if (!current_user_can('manage_options'))  {
                wp_die( __('You do not have sufficient permissions to access this page.') );
        }
        echo '<div class="wrap">';
        echo '<h3>User Details</h3>';
        echo '</div>';
}
?>

Within the top comment area, WordPress expects some information about your plugin, such as the plugin name and version. There's a single action hook that runs the function "jp_email_user" right whenever a post gets published. Combine this file with a readme.txt file and you are all done. This is about as simple as it gets. Hooks are great because they allow you to change how WordPress works without needing to touch any core code. Much of the WordPress code can be "hooked" into, allowing for an extremely high level of flexibility, comparable to Drupal. Best of all, since there are so many plugins already in the repository, there is likely one that already does what you need. If not, there are thousands of working examples to guide you towards creating your very own plugin