This is part 2 of 3 in the Creating a Basic Plugin Tutorial.
Writing a Basic Plugin – Template Tags
Writing a Basic Plugin – Templates
Now that you have gone through the base foundation of a plugin, let’s look at how to make it easy to use(in a theme) and somewhat extendable.
I should mention that overridable template tags is not the most flexible and future-proof way of making your plugin extendable and I wouldn’t suggest going down this road if you are going to write a public plugin designated for either WordPress.org, GitHub or another means for mass distribution.
Overridable template tags are better-suited for utility plugins designated for a specific project(or a limited set of projects). I’m saying this, because what they provide is a quick way for overriding specific functionality provided by the plugin, without modifying the plugin itself. Of course if the plugin is updated, you might still need to adjust the corresponding override in the theme, but the chances are that you will be doing the plugin update anyway, so you will be able to handle that.
The first thing you need to do is create a new file in your plugin directory called template-tags.php
. In it you can add this code:
<?php if ( ! defined( 'ABSPATH' ) ) { return; } if ( ! function_exists( 'basic_plugin_hello_world' ) ) { function basic_plugin_hello_world() { echo 'Hello World!'; } }
This is pretty much what every child-ready theme does in order to allow it’s template tags to be overwritten by the child theme. Before registering the function basic_plugin_hello_world()
, you simply check to make sure it doesn’t already exist.
Now in order to actually run the above code, it needs to be included. Adding to our Foundation, we will register a callback function for the after_setup_theme
action:
protected static function add_actions() { add_action( 'after_setup_theme', array( __CLASS__, 'include_template_tags' ), 10 ); } public static function include_template_tags() { include_once( plugin_dir_path( __FILE__ ) . 'template-tags.php' ); }
Now once all of the theme files have been included, you will include your template-tags.php
file and the template tags will be available from within the theme.