How to create a WordPress plugin

Design interactivity

This post was originally published on September 24, 2015 and updated on November 10, 2017.

Many businesses and marketers building WordPress sites tend to see them as their online brochures — digital marketing channels that build awareness, capture search traffic, engage social traffic, and convert that traffic into new business. While there’s no doubt this strategy works, it limits the potential of a WordPress site.

A WordPress website can be a far more interactive experience for your visitors.

 
A benefit of interactive tools on your site is that most of your visitors are interactive learners. They’ll read a page subhead that claims site visitors will save 20 percent on your service, but calculating the actual amount leaves a much more impressionable result.

Create a WordPress plugin to add unique interactivity to your site.

Building a calculator into your WordPress site is one example of designing interactivity. Perhaps visitors are wondering how much money they could save by switching to your service. Maybe they need a quote based on dimensions or quantities. Or perhaps they wish to calculate a loan payoff. When you provide a calculator on your WordPress site to meet these needs, you can engage visitors and position your site as a useful resource.

WordPress developers often hard-code functionality like this into a theme. The problem, though, is that interactive content is not a design element — it’s content. If you decide to update your theme, do you want the additional cost of integrating the calculator into the new theme? By developing the calculator as a plugin instead, you can migrate your theme and the calculator will continue to to function as designed.

How do you create a WordPress plugin?

To create a WordPress plugin, follow these steps:

  1. Understand the structure of WordPress plugins.

  2. Plan for your plugin customization and configuration options.

  3. Write the code that puts it all together.

Let’s get into it.

Understanding WordPress plugins

WordPress published a WordPress Plugin Handbook with every detail of plugin development. As you use this article to jump-start writing your first plugin, refer to that guide as needed. It’s helpful.

WordPress plugins have a simple construction process where there’s a zipped file that contains the follow elements.

Single Parent Folder

All of your plugin’s assets and description files are contained in a single folder. The folder is named lowercase with only alphanumeric numbers or dashes (but no spaces).

PHP File Declaration

Begin with a single PHP file in your parent folder that tells WordPress that the file is a plugin. This is accomplished by simply adding the following comment on your file:


/*
Plugin Name: Savings Calculator
*/

That’s it! If you zipped up the file and folder into a zip file and uploaded it to your server, you could install and activate that plugin as is. It doesn’t do anything, of course! But technically, it’s now a plugin!

Plugins-wp
As you can see, it’s fairly light on details. I’d highly recommend adding a description and version. If you’re developing the plugin for a client or another company, you should probably add your author and author site as well:


/*
Plugin Name: Savings Calculator
Description: Calculate the savings of switching over to our service.
Version: 1.0
Author: Douglas Karr
Author URI: http://www.dknewmedia.com
*/

The result is much more informative on your plugins page:

plugin2-wp

Pre-planning plugin customization

Just as we want to be able to update themes and not impact our plugin, we also want to ensure that we can update our calculator easily when there are changes to our internal pricing. Say we offer a product for $4.99; the price might change to $5.99. Rather than having to edit our plugin, why not just have an administrative setting where we can modify our product cost?

To manage price updates, we must add an administrative menu item that will open a page to update our pricing. To insert the calculator into a page or post, we’ll also need to program a shortcode into the plugin. The shortcode will insert a form into your content where the user can post their pricing and make a comparison.

Be sure to name your PHP functions and variables uniquely to avoid conflicts with other plugins or themes.

Our Savings Calculator plugin

The first step in developing our plugin (after writing our header) is to initialize the plugin and add our menu:


// Initialize the plugin and add the menu
add_action( 'admin_menu', 'sc_add_admin_menu' );
add_action( 'admin_init', 'sc_settings_init' );

Next, we want to specify the function that’s called by the menu to display the options page:


// Add an Admin Menu option for Settings
function sc_add_admin_menu( ) {
add_options_page( 'Savings Calculator', 'Savings Calculator',
'manage_options', 'savings_calculator', 'savings_calculator_options_page' );
}

We must register the settings for our plugin:


// Add the Savings Calculator settings to the Settings Page
function sc_settings_init( ) {
register_setting( 'pluginPage', 'sc_settings' );
add_settings_section(
'sc_pluginPage_section',
__( 'Settings Page', 'sc_' ),
'sc_settings_section_callback',
'pluginPage'
);
add_settings_field(
'sc_oldamount',
__( 'Amount', 'sc_' ),
'sc_oldamount_render',
'pluginPage',
'sc_pluginPage_section'
);
}

Within the settings call above, we call a function to render the default amount field:


// Set the settings input field to render
function sc_oldamount_render() {
$options = get_option( 'sc_settings' );
?>
;'>
<?php
}

We need to combine and publish the settings section:


// Build the Administrative form to save the default amount
function savings_calculator_options_page() {
?>
<form action='options.php' method='post'>
<h2>Savings Calculator<:/h2>
<?php
settings_fields( 'pluginPage' );
do_settings_sections( 'pluginPage' );
submit_button();
?>
</form>
<h3>Savings Calculator Usage</h3>
<p>Examples of shortcode usage:</p>
<ul>
<li><strong>[savingscalculator symbol="$"]</strong> - publishes the form using the US dollar sign to the left of the currency amount.</li>
<li><strong>[savingscalculator amount="9.99" symbol="$"]</strong> - publishes the form calculated to the custom amount rather than default.</li>
<li><strong>[savingscalculator symbol="$"]Fill in the Amount You Are Currently Paying:[/savingscalculator]</strong> - publishes the form with instructions before the form.</li>
<li><strong>[savingscalculator position="right" symbol=" ¥"]</strong> - publishes the form using the US dollar sign to the left of the currency amount.</li>
<</ul> <?php }

Even with a simple plugin like this, it’s good to add supporting documentation to your settings page. We’ve included four different ways of writing the shortcode.

screenshot-settings-page

We’ve set up our Administrative Menu and Settings options; now we can begin writing our code to display the savings calculator in place of the shortcode utilized within the content.


// Register and return the shortcode
function savingscalculator( $atts, $content = null ) {
if( is_array( $atts ) ) extract($atts);
$options = get_option( 'sc_settings' );
if($amount == null ) { $oldamount = $options['sc_oldamount']; } else { $oldamount = $amount; }
return $content.sc_buildform($position, $symbol, $oldamount);
}
add_shortcode('savingscalculator', 'savingscalculator');

Let’s put together the core of our plugin code — the form, post validation and resulting calculations output.


// Build the form to display
function sc_buildform($position, $symbol, $oldamount) {
if(is_numeric($_POST['newamount'])) {
$sc_newamount = $_POST['newamount'];
}
$sc_form = '';
if ( !empty($_POST) && !is_numeric($sc_newamount) ) { $sc_form .= 'You must enter a numeric amount.'; }
$sc_form .= '

';
$sc_form .= '

: ';
$sc_form .= '';
$sc_form .= '';
$sc_form .= '

';
$sc_form .= '

';
if ( !empty($_POST) ) {
$sc_diff = round($sc_newamount - $oldamount, 2);
$sc_percent = round(($sc_newamount - $oldamount) * 100 / $oldamount, 1);
if($position=="right") {
$sc_currency = $sc_diff.$symbol;
$sc_oldamount = $oldamount.$symbol;
} else {
$sc_currency = $symbol.$sc_diff;
$sc_oldamount = $symbol.$oldamount;
}
if($sc_diff > 0) {
$sc_form .= '

Great News! You\'re going to save '.$sc_currency.' ('.$sc_percent.'%) over our price of '.$sc_oldamount.'!

';
} elseif ($sc_diff < 0) { $sc_form .= '

You\'re already saving '.$sc_currency.' ('.$sc_percent.'%) over our price of '.$sc_oldamount.'

';
} elseif ($sc_diff == 0) {
$sc_form .= '

Well, you\'re already getting a great deal over our price of '.$sc_oldamount.' and aren\'t going to save anything.

';
}
}
return $sc_form;
}

Pro tip: Do not leave spaces or line returns after you close your PHP file. Plugins are executed inline with your WordPress site, and extra spacing can cause visible issues with your site.

Once activated, you can now set your default amount on the Settings page and insert the shortcode into your content:

screenshot-page-edit

The result is a simple little form that builds an interactive Savings Calculator within any content on your WordPress site:

screenshot-result

You can test our Savings Calculator on our demonstration site. Download our plugin and feel free to customize it for your WordPress site!

And congratulations on building your first WordPress plugin.

Image by: Johnnie Utah via Compfight cc

Douglas Karr

Douglas is a marketing technology expert, working with key industry players, corporations and startups for over a decade. As the CEO of his consultancy, DK New Media, he consults and develops strategies for assisting marketing technology companies gain market share as well as enterprise corporations with vendor selection. He advises investors and venture capital firms. He’s also been integrating, developing, and optimizing WordPress since version 1.5 when he founded his Marketing Technology blog.