Creating a WordPress plugin

Posted by Matt Thommes on October 23, 2009 | Post type: Gain

The WordPress codex explains plugins from a reference perspective, but the best way to learn is to see real-world code examples of basic plugins that demonstrate how to set things up for beginners.

This tutorial is an overview for a basic plugin that uses PHP to save and retrieve data from the WordPress database to display on the site.

Here are the steps:

  1. Create a PHP file.

  2. Set up two functions - one for public, one for admin.

  3. Call necessary code to register the plugin with WordPress.

Create a PHP file

First, create a PHP file in a folder with a unique name - this folder will reside in the same folder as other plugins, so it can't be named the same as anything else.

This will be the file where all of your scripting for the plugin will reside.

Set up two functions - one for public, one for admin

In the PHP file, start by creating two functions:

function mywidget_public($args = false) {

}

function mywidget_admin() {

}

Our widget, for example purposes, is called "My Widget," which we'll reference as "mywidget_" in the code. These two functions are the skeleton for PHP code that will run when users visit the public side of your WordPress site - on whatever page you place the widget (we'll get to that shortly), as well as the admin side when an admin user drags your widget to a sidebar panel (under the Appearance > Widgets section):

Screenshot of WordPress admin section

Feel free to put any PHP code in both of those functions - whatever you wish to run.

In the admin function, you're basically setting up an HTML form for users to control settings related to your widget:

Screenshot of WordPress admin section

In the example screenshot above, we're asking users for information pertaining to making an API call (you can put anything here - this is just an example).

So, for starters, the admin function could look like this:

function mywidget_admin() {

  $options_site = get_option("widget_mywidget_site");

  ?>

        <p>
            Your Software URL:
            <input type="text" name="p_link" id="p_link" value="<?php echo $options_site["p_link"]; ?>" style="width:99%;" />
        </p>

        <p>
            Your Software Username:
            <input type="text" name="username" id="username" value="<?php echo $options_site["username"]; ?>" style="width:99%;" />
        </p>

        <p>
            Your Software Password:
            <input type="password" name="password" id="password" value="<?php echo $options_site["password"]; ?>" style="width:99%;" />
        </p>

  <?php

}

Notice, specifically, the value attributes for each <input> element. We reference the variable $options_site, which is declared before the HTML is output. $options_site calls a WordPress function, get_option(), which retrieves values from the WordPress database.

If you're wondering how the values get to the database in the first place, they do so by calling another WordPress function: update_option().

Let's take a look at the syntax for saving values to the database:

update_option("widget_mywidget_site", $options_site);

The function update_option accepts two parameters. The first is the unique name you'll use to reference these database values in your scripts. The second is the variable you are saving to the database. You can pass an array here too - which is useful for collections of values related to each other.

Your values are saved to the wp_options database table. Values submitted as arrays will be serialized.

Screenshot of phpMyAdmin

You can create as many distinct "options" as you'd like, and all can be saved to the database.

Continuing with the admin function, when someone fills in the details, and hits the "Save" button (this button is generated by WordPress automatically - you don't need to create it in your HTML form), you should call the update_option function and pass the values in.

So, to modify the admin function a little bit:

function mywidget_admin() {

  $options_site = get_option("widget_mywidget_site");

  if ($_SERVER["REQUEST_METHOD"] == "POST") {

      $options_site = array(

          "p_link" => $_POST["p_link"],
          "username" => $_POST["username"],
          "password" => $_POST["password"],

      );

      update_option("widget_mywidget_site", $options_site);

  }
  else {

      ?>

            <p>
                Your Software URL:
                <input type="text" name="p_link" id="p_link" value="<?php echo $options_site["p_link"]; ?>" style="width:99%;" />
            </p>

            <p>
                Your Software Username:
                <input type="text" name="username" id="username" value="<?php echo $options_site["username"]; ?>" style="width:99%;" />
            </p>

            <p>
                Your Software Password:
                <input type="password" name="password" id="password" value="<?php echo $options_site["password"]; ?>" style="width:99%;" />
            </p>

      <?php

  }

}

Here we check to see if the "Save" button was hit (if ($_SERVER["REQUEST_METHOD"] == "POST")), and if so, create an array for the form values, and update the database.

In your public function, you can retrieve the database values to display on the site:

function mywidget_public($args = false) {

  $options_site = get_option("widget_mywidget_site");

  echo $options_site["html"];

}

It's as simple as that. Provided there is an "html" array item in $options_site, this will display the "html" contents into the sidebar on the public side of your WordPress site. (We assume that when the user submits their admin details, the script does an API call to fetch HTML content from another domain - you'd have to write this code though, using curl or something like that.)

Call necessary code to register the plugin with WordPress

The example I provided was bare-bones and simple. There's a few more things we should do before the widget is recognized, and works with the WordPress system.

At the bottom of your PHP file, include this code:

function widget_mywidget_init() {
    register_sidebar_widget("My Widget", "widget_mywidget_public");
    register_widget_control("My Widget", 'widget_mywidget_admin');
}

add_action("plugins_loaded", "widget_mywidget_init");

This will load the plugin on the admin page, so users can actually activate it.

Wrap-up

That's the basic steps! There's plenty more involved for those that care, but this tutorial was just a quick demonstration of creating a WordPress plugin with code samples.

Read the official WordPress plugin documentation to get more details.

About the author(s)

Matt Thommes is an independent publishing enthusiast, mobile blogger, content creator, informative writer, web developer from a suburb of Chicago. Never one to conform, Matt intends to promote the effect the web has on our lives, in an effort to intensify, instruct, and clarify all that is happening around us.

Comments

Note: Comments may be viewed by authors, but if you have a more specific question you'd like to ask them, please email matt.thommes@paininthetech.com.