Create your own WordPress toolkit
Matt Cohen and Scott Basgaard of WooThemes show how to create a WordPress plug-in to enhance your custom WordPress projects, using best practices in plug-in development
Download the support files for this WordPress tutorial.
Since its inception back in 2003, WordPress has evolved from a blogging platform into a fully-fledged content management system. This process of evolution has spawned a new industry within the WordPress ecosystem, offering paid-for WordPress themes, plug-ins and other services.
While custom development work on projects is often an ideal route, it isn’t always the most efficient in terms of getting the task done. When using WordPress in combination with paid-for WordPress products, it’s often difficult to sell the customer on the concept of: ‘I am doing the job for you, and am using these third-party paid-for products to do so’.
In this tutorial, we’ll be discussing how to create a unique upsell for your customers, through a customised toolkit plug-in, to enhance your WordPress-powered projects.
We’re not in Kansas any more … but where are we?
Before diving into our toolkit, it’s important that we fully assess the environment we’re working in. While we may not need to make environment-based decisions on each project, the plug-ins we have in place could help to save us time on certain projects.
On a project using paid-for products such as Canvas by WooThemes and Gravity Forms by Rocket Genius, we can instantly see that it’s possible for us to leverage the power of Canvas’s custom hooks to display custom forms (managed using Gravity Forms) at various points in our website.
While our environment can play a role in how we approach the project, here we’ll be working specifically with built-in WordPress functionality.
Little boxes, on the hillside…
As a best practice, it is important for us to separate our code from the paid-for products, in order to ensure smooth upgrades when new versions are released.
For example, if we need to customise Gravity Forms on a project, we’ll create an additional plug-in that uses Gravity Form’s hooks and filters to do so. This may require some additional digging around and familiarising yourself with Gravity Forms.
If you’re customising a theme, we’d recommend that you use a child theme. If you are already using one of these, we’d also recommend storing your customisations in a separate plug-in. Developers often view each child theme as an individual project – but this shouldn’t be the case, because the child theme should consist purely of styling and visual adjustments to the theme.
While this may seem obvious, it is often not taken into account during the early stages of a project’s development. This is important in order for our toolkit to scale well across a wide array of projects.
Actions, filters and starter features
Many developers aren’t aware of the many powerful hooks that exist in every WordPress installation. Actions and filters can easily be shifted from a theme to a plug-in environment. That way you can maintain a single codebase and activate that plug-in across multiple installations.
Every time the WordPress Loop runs, at least three actions are executed: loop_start, the_post and loop_end. We can leverage these, along with conditional tags, to display and manipulate content in any loop being displayed on screen … from within our plug-in!
Now that we understand what we’re going to be doing – and how – let’s get a few starter features together that we can include in our plug-in:
Get the Creative Bloq Newsletter
Daily design news, reviews, how-tos and more, as picked by the editors.
- Hide the generator meta tag in the WordPress header.
- Specify a Google Analytics ID, and an option to select whether the code should output in the header or footer section of the website.
- Display advertising code after every X posts on archive screens.
- Perform the above without storing any data in the database or creating settings screens within the WordPress admin.
Let’s get to work!
Code structure
A few aspects of the plug-in are key to the code scaling well and avoiding conflicts with other code; we’ll use a PHP class to store our code and initialise on the plug-ins_loaded hook. This ensures our code is free of naming conflicts, and that all plug-ins are fully loaded prior to it executing, meaning we can take advantage of functionality offered by other plug-ins.
Class properties
At the beginning of our class, we define a collection of properties which will be used within our toolkit. For reference, these are as follows:
public $tracking_id = '';
public $tracking_location = 'footer';
public $advertising_code = '';
public $display_every_x = 3;
private $_post_counter = 0;
The init() method
In our class constructor (the function that runs when executing our class at the bottom of the plug-in), we add a hook on plug-ins_loaded, which runs our init() method. This is where the main logic behind the turning on and off of our functionality takes place. Hooking it onto the plug-ins_loaded hook ensures we have access to all activated plug-ins, prior to executing our code.
The remove_generator_tag() method
This is our simplest method in the plug-in; call remove_action() to remove the wp_generator function from the wp_head section. This is the simplest form of WordPress plug-in development.
The display_google_analytics_code() method
This is our more intermediate method, where we output a Google Analytics tracking code. This is common practice across websites and is often handled within a theme. Why not handle this in your toolkit plug-in instead?
This method looks to some internal properties which you would set either in your theme or in a separate ‘loader’ plug-in, of sorts. This would enable you to update and maintain your toolkit plug-in across multiple WordPress installations, without having to keep track of different modified versions. You would set the tracking ID and tracking location as follows:
global $yourname_wordpress_toolkit;
$yourname_wordpress_toolkit->tracking_id = 'your_tracking_id_here';
$yourname_wordpress_toolkit->tracking_location = 'header';
Our init() method above handles the logic for where the Google Analytics code is to be displayed (either in the header or footer section). We then keep the display method as clean as possible, because it has only the one task of displaying the code, rather than determining where the display should occur.
The display_advertising_code() method
This is the most complex of the three functions of our toolkit. This method is hooked onto the the_post hook and uses the internal $_post_counter property to keep track of how many posts have been displayed in the loop. We then check if we’re on a multiple of the desired number of posts between each advertising code, and if we are, we retrieve the advertising code (using the get_advertising_code() method) and display it.
You would set the number of posts between advertising codes and the advertising code itself as follows in your theme or loader plug-in:
global $yourname_wordpress_toolkit;
$yourname_wordpress_toolkit->display_every_x = 3;
$yourname_wordpress_toolkit->advertising_code = your_advertising_code_here;
Instantiate the class
At the very end of our plug-in file, just before we close our PHP tags, we need to instantiate the class itself. This is done using the following code:
global $yourname_wordpress_toolkit;
$yourname_wordpress_toolkit = new YourName_WordPress_Toolkit();
The finished plug-in
Our starter toolkit plug-in is now complete. Save the following into a file called yourname-wordpress-toolkit.php in your wp-content/plug-ins folder:
<?php
/**
* Plugin Name: Your WordPress Toolkit
* Plugin URI: http://your-website-url-here.com/your-wordpress-toolkit/
* Description: Hi, I'm Your WordPress Toolkit, a collection of awesome functionality used to enhance your WordPress-powered website and provide extra functionality on top of paid-for WordPress products used by our agency.
* Author: Matt Cohen and Scott Basgaard of WooThemes
* Version: 1.0.0
* Author URI: http://woothemes.com/
*/
if ( ! class_exists( 'YourName_WordPress_Toolkit' ) ) {
class YourName_WordPress_Toolkit {
public $tracking_id = '';
public $tracking_location = 'footer';
public $advertising_code = '';
public $display_every_x = 3;
private $_post_counter = 0;
public function __construct () {
add_action( 'plug-ins_loaded', array( &$this, 'init' ) );
} // End __construct()
public function init () {
// Remove the "generator" meta tag.
if ( ! is_admin() ) { $this->remove_generator_tag(); }
// Load Google Analytics tracking code.
if ( ! is_admin() && ( '' != $this->tracking_id ) ) {
if ( 'header' == $this->tracking_location ) {
add_action( 'wp_print_scripts', array( &$this, 'display_google_analytics_code' ) );
} else {
add_action( 'wp_footer', array( &$this, 'display_google_analytics_code' ) );
}
}
// Display advertising code after every "X" posts.
if ( ! is_admin() && ! is_singular() && ( '' != $this->advertising_code ) ) {
add_action( 'the_post', array( &$this, 'display_advertising_code' ) );
}
} // End init()
public function remove_generator_tag () {
remove_action( 'wp_head', 'wp_generator' );
} // End remove_generator_tag()
public function display_google_analytics_code () {
if ( '' == $this->tracking_id ) { return; }
$html = '<script type="text/javascript">//<![CDATA[
var _gaq = _gaq || [];
_gaq.push([\'_setAccount\', \'' . esc_js( $this->tracking_id ) . '\']);
_gaq.push([\'_trackPageview\']);
(function () {
var ga = document.createElement(\'script\');
ga.type = \'text/javascript\';
ga.async = true;
ga.src = (\'https:\' == document.location.protocol ? \'https://'ssl\' : \'http://www\') + \'.google-analytics.com/ga.js\';
var s = document.getElementsByTagName(\'script\')[0];
s.parentNode.insertBefore(ga, s);
})();
//]]></script>' . "\n";
echo $html;
} // End display_google_analytics_code()
public function display_advertising_code ( $obj ) {
if ( is_main_query() && in_the_loop() ) {
if ( ( 1 < $this->_post_counter ) && ( 0 == $this->_post_counter % $this->display_every_x ) ) {
echo $this->get_advertising_code();
}
$this->_post_counter++;
}
} // End display_advertising_code()
private function get_advertising_code () {
return wp_kses_post( trim( $this->advertising_code ) );
} // End get_advertising_code()
} // End Class
}
global $yourname_wordpress_toolkit;
$yourname_wordpress_toolkit = new YourName_WordPress_Toolkit();
?>
Building a castle around a keep
That’s it – you’re now ready to set yourself apart from all those other agencies and freelancers using WordPress by providing a unique offering to your customers.
Take your paid-for WordPress products to the next level, enhance the experience your customers enjoy on your projects and build out your toolkit, both to save you time and to have fun while building exciting projects for your customers.
Thank you for reading 5 articles this month* Join now for unlimited access
Enjoy your first month for just £1 / $1 / €1
*Read 5 free articles per month without a subscription
Join now for unlimited access
Try first month for just £1 / $1 / €1
The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.