Useful Snippets


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at

RSS Latest posts from my personal blog

Most viewed posts

Subscribe to RSS feed

WordPress Object-oriented plugin skeleton

Stanislav KhromovStanislav Khromov

A quick OOP pattern / skeleton for creating WordPress plugins.

Plugin Name: Your Plugin
Plugin URI:
Description: Your plugin skeleton
Version: 1.0
Author: you
Author URI:
License: GPL2

/* The class encapsulates the plugin and its functions */
class Your_Plugin
    /* Put any plugin variables here */
    var $plugin_variable;

    /* The constructor will be used to setup actions and filters */
    function __construct()
         * Set a plugin variable
        $this->plugin_variable = 'test';

         * Hook on plugins_loaded. This is the first hook available to regular plugins.
         * It happens when all plugins have been initialized and is the best place to put your logic.
        add_action('plugins_loaded', array($this, 'plugin_loaded'));

        /* Optionally, add additional hooks here. */

     * Put your main plugin logic here!
    function plugin_loaded()
        /* Here is how to call a function inside your class: */
        $sum = $this->add(1,2);

     * A plugin function that adds
     * two numbers together and
     * returns them.
     * @param $var1
     * @param $var2
     * @return mixed
    function add($var1, $var2)
        return $var1+$var2;

/* This initiates your plugin */
$your_plugin = new Your_Plugin();

Interfacing with your plugin

Interfacing with your plugin is possible by either calling the global you created (last line), like this:

global $your_plugin;
$sum = $your_plugin->add(1,2);

If you hooked on plugins_loaded, this can be done pretty much anywhere – other plugins, themes, you name it!

Another popular pattern is creating a global function helper inside your plugin.

 * Here is how to create a global function
 * for your plugin.
function your_plugin_add($var1, $var2)
    global $your_plugin;
    return $your_plugin->add($var1,  $var2);

And here is how you would call the global function in that case:

 * Here is how to call the external function:
$sum = your_plugin_add(1,2);

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
Twitter Profile
Visit my other blog

Comments 0
There are currently no comments.