This is part 1 of 3 in the Creating a Basic Plugin Tutorial.
Writing a Basic Plugin – The Foundation
Writing a Basic Plugin – Templates
In this part of the tutorial I will show you the very foundation of the plugins I write. I’ve recently found myself writing plugins by using one or more classes that provide only static interfaces(and if necessary I add some template tags that can be overwritten in the theme).
In it’s simplest form, the plugin looks like this:
<?php /** * Plugin Name: Basic Plugin * Plugin Author: Paiyak Development * Author URI: https://paiyakdev.com * Description: A very basic plugin */ /** * A sample base plugin */ class Basic_Plugin { public static function start() { static $started = false; if ( ! $started ) { self::add_filters(); self::add_actions(); $started = true; } } protected static function add_filters() { // Add all filters here } protected static function add_actions() { // Add all actions here } } Basic_Plugin::start();
What happens here is that we register a class called Basic_Plugin
. In that class we have three methods: Basic_Plugin::start()
, Basic_Plugin::add_filters()
and Basic_Plugin::add_actions()
.
The first method – Basic_Plugin::start()
is what we call in order to initialize the plugin(I have added a simple fail-check to avoid double initialization – you can still get around it, but it probably won’t be worth the effort). At this point, the initialization basically consists of hooking any filters and actions to be ran at a later point.
From now on, you can add a filter like so(only partial code is below):
protected static function add_filters() { add_filter( 'the_content', array( __CLASS__, 'filter_the_content' ), 8 ); } public static function filter_the_content( $content ) { return "Hello World!\n\n" . $content; }
Note the use of the magic constant __CLASS__
– I’ve found it to save me some typing, because I can create Sublime Text Snippets that will work within any class(you can do the same if you decide to go with non-static functions, where you can use $this
).
You can also hook to the init
action and/or use class variables(protected static $my_var = '';
) in order to do some more advanced initialization of the plugin.
With this, I’ll conclude this part of the tutorial, since you now have a simple and flexible base for your plugin.