028_TF_Herman_Build-a-Simple-Plugin-with-OptionsTitan Framework is built to make flexible and dynamic plugins easier to make. Instead of having to deal with the heavy lifting of writing options, functions and updating values, it takes and encapsulates them in a simple class call, array-based setting, and a class-based option value fetching. Titan Framework also handles menu page building for you!

But like all things, you have to start somewhere. On one glance, it looks like an insurmountable mountain of complex sophistication, but peel back the surface and you’ll find out it’s not that hard to understand.

Then again, where do you start?

For this, you’ll need:

  1. An environment where you can play around with your WordPress installation. (XAMPP, MAMP, and the like will do)
  2. A copy of WordPress running.
  3. A text editor.
  4. A copy of the Titan Framework installed and activated.

To understand the basics of how a plugin works, let’s take a good example of an existing simplistic WordPress plugin. In this case, the “Hello Dolly” plugin by Matt Mullenweg which is nothing more than random lyric lines of “Hello Dolly” appearing in your Admin backend.

Apart from being your usual PHP file, a WordPress plugin contains the Plugin Header. This part is crucial for it recognizes your file in WordPress as a plugin. It is written as a PHP file comment right after the PHP header, and then parsed by WordPress.

/*
Plugin Name: Hello Dolly
Plugin URI: http://wordpress.org/plugins/hello-dolly/
Description: This is not just a plugin, it symbolizes the hope and enthusiasm of an entire generation summed up in two words sung most famously by Louis Armstrong: Hello, Dolly. When activated you will randomly see a lyric from Hello, Dolly in the upper right of your admin screen on every page.
Author: Matt Mullenweg
Version: 1.6
Author URI: http://ma.tt/
*/​

Plugin Name is obviously, the name of your plugin.
Plugin URI is where the plugin’s published URL is. Right now, as you’re merely getting started, this line can be ignored for now.
Description is a simplistic statement of what your plugin does, what it can do, and such.
Author is the name of who built the plugin. Obviously, your name will go here when you make your own plugin.
Version is the numbered iteration of your plugin as it progresses with updates. As you’re merely getting started, this will always be at 1.0
Author URI is where your homepage, profile, or other website you can be reached can be written.

The items Plugin Name, Description, Author and Version are mandatory in any WordPress plugin. There are other fields in the header not found in this plugin, but for now, let’s set our sights in these mentioned fields.


Now, let’s build our first Titan Framework based plugin!

  1. Browse to your plugins folder. (usually /www/wp-content/plugins) Depending on your webserver, the location of your wp-content folder may vary.
  2. In the plugins folder, let’s create a folder for our example plugin: titan-radio
  3. Go to your newly-created folder and create a new PHP file. Let’s name this new PHP file as titan-radio.php
  4. Now go to your Titan Framework folder in the plugins folder. Here, you’ll have to include the framework checker to bridge your plugin and the Titan Framework together.

We recommend using the Titan Framework checker, as it is considered the best practice, especially if you will be selling plugins or publishing them in WordPress’ plugin repository. Copy titan-framework-checker.php from the Titan Framework folder and paste it to your plugin folder. Users of your plugin must download and activate Titan Framework first before your plugin can be used.

With the files in place, it’s time to write the contents of the plugin!

  1. Open titan-radio.php in any text editor or IDE of your choice.
  2. Add the PHP header.
  3. Add the plugin info header, with the customizations in place.
  4. Add the PHP terminator at the end of the file.

Below the plugin info header is where we’ll write the code. We are going to create our first plugin, which we called Titan Radio. It’s inspired by the Hello Dolly plugin, but instead of simply Hello Dolly, we can change it into lyrics of whatever song we have in mind.

  1. Include Titan Framework. Add the line:
    include('titan-framework-checker.php');

    The file titan-framework-checker.php will warn users who don’t have Titan Framework activated. No further checking of the framework’s existence is needed as the file does it all for you.

  1. Create the function that will house the options. The function code is coupled with an action hook. This hook will tell the Titan Framework to initialize the options for usage. Remember to make your function names unique and observe namespacing, to prevent any likelihood of conflicts.
    // Initialize options, called only when Titan Framework exists. function create_radio_options() { // Do stuff here. } // Call this and the options now exist. add_action( 'tf_create_options', 'create_radio_options' );
  1. Inside the function, add this line:
    $titan = TitanFramework::getInstance( 'titan-radio' );

    This will identify your usage instance of Titan Framework, and will be vital.

  1. Now add the code that defines the admin panel to allow your plugin to present an options page for its settings. You’ll notice there’s some parameters that needs to be understood.
    $admin_panel = $titan->createAdminPanel( array( 'name' => 'Titan Radio Options', 'id' => 'titan-radio', 'parent' => 'options-general.php', ) );

    Name is obviously the name of the settings page you’ll be creating, id is the system identifier of the admin panel, and parent is where the admin panel will be hooked from, which is the general settings page in the admin backend panel. Again, in picking ids, they should be unique as well.

  1. Let’s add the input field where lyrics can be added. The option parameters are straightforward like with name, with id as the unique identifier, and desc as the general description of the option.
    $admin_panel->createOption( array( 'name' => 'Lyrics', 'id' => 'my_lyrics', 'type' => 'textarea', 'desc' => 'Enter your lyrics here, with each lines separated by new lines' ) );
  1. And finally, let’s give it the ability to save and reset options.
    $admin_panel->createOption( array( 'type' => 'save', ) );

Now the real work begins: making the functionality. Several functions will be written that will comprise of the inner workings of the plugin.

Vital to anything in regards to working with Titan Framework is the ability to retrieve stored values. Here’s an example:

$titan->getOption('my_lyrics');​

You’ve seen the my_lyrics id earlier in the textarea option, right? What this code does is telling the Titan Framework to pull data originating from the my_lyrics id. These values are also stored in the database similar to how WordPress natively does. Depending on the options written, it will return a string or array value. How you process the value is up to you. For this example, it will return a string value, since it is where the lyrics will be coming from.

Refer to the function below for one of the function, and its explanation. This shall be added right below the options you’ve just written.

// Prime the lyrics for random picking.
function show_radio_lyrics() {
// Check if Titan Framework exists. Exit right away if it doesn’t exist.
if ( !class_exists('TitanFramework') ) {
return false;
}
// Initialize Titan Framework.
$titan = TitanFramework::getInstance( 'titan-radio' );
// Fetch the lyrics from the options with the id my_lyrics.
$lyrics = $titan->getOption('my_lyrics');
// Make sure the lyrics are there and not empty. Else, return false.
if ( empty( $lyrics ) ) {
return false;
}
// Split the lyrics into array objects so it would be easier to randomize.
$lyrics = explode( PHP_EOL, $lyrics );
// Return a random line of the lyric.
return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) – 1 ) ] );
}​

You’ll notice we return false if either Titan Framework doesn’t exist or the options retrieval yields an empty value. This is to ensure graceful error handling in the event the plugin is run without Titan Framework activated, or the field value is not populated.

Now that we’ve written how the stored value is processed, how do we now show it? The code below has the answer. Add this next.

// Echo the chosen line, or a notice that you can do so.
function show_the_radio() {
      $chosen = show_radio_lyrics();
      $output = $chosen ? '♫ ' . $chosen . ' ♫' : 'Your song can go in here! Check the admin options for details!';
      echo '<p style=”text-align: center;”>' . $output . '</p>';
}​

The code is nothing more than a value validation, ensuring there is strings returned. Should the function show_radio_lyrics return false, it will fall back to a generic string and will not result in a blank output. Once the string output is established, the value, along with an html tag, is now echoed. This function must echo its contents as it will pass through an action hook, as seen below.

// Now we set that function up to execute when the admin_notices action is called.
add_action( ‘admin_notices’, ‘show_the_radio’ );​

Put everything together, save, and activate it, with Titan Framework, if you chose the checker instead of the embedder.

If you see the lines on top of your admin area as “Your song can go in here! Check the admin options for details!”, and no errors came up, you have done it.


The hard part is now over. Now it’s time to have some fun with your newly built plugin!

Go now to the Settings tab, and look for the Gambit Radio entry. Click it.

See the newly created text field there? Put this line below here (or your other lyrics, if you so choose)

Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you

Paste, save, and watch a random line of that lyrics appear!

Congratulations! You have just created your very first Titan Framework plugin.

How well did you fare? Here’s the completed product to compare against.

Alternatively, here’s how the entire plugin should look like:

<?php
/*
Plugin Name: Titan Radio
Plugin URI: http://www.gambit.ph
Description: Why settle for Hello Dolly? Put in your song of your choice and watch its lines randomly appear in the admin backend!
Author: You
Version: 1.6
Author URI: http://www.gambit.ph
*/
// Include Titan Framework
include(‘titan-framework-checker.php’);
// Initialize options, called only when Titan Framework exists.
function create_radio_options() {
    // Initialize Titan Framework.
    $titan = TitanFramework::getInstance( ‘titan-radio’ );
    // Creates the Admin panel.
    $admin_panel = $titan->createAdminPanel( array(
        ‘name’ => ‘Titan Radio’,
        ‘id’ => ‘titan-radio’,
        ‘parent’ => ‘options-general.php’,
    ) );
    // Allows text entry.
    $admin_panel->createOption( array(
        ‘name’ => ‘Lyrics’,
        ‘id’ => ‘my_lyrics’,
        ‘type’ => ‘textarea’,
        ‘desc’ => ‘Enter your lyrics here, with each lines separated by new lines. Eliminate blank lines.’
    ) );
    // Save or reset.
    $admin_panel->createOption( array(
        ‘type’ => ‘save’,
    ) );
}
// Call this and the options now exist.
add_action( ‘tf_create_options’, ‘create_radio_options’ );
// Prime the lyrics for random picking.
function show_radio_lyrics() {
    // Check if Titan Framework exists. Exit right away if it doesn’t exist.
    if ( !class_exists(‘TitanFramework’) ) {
        return false;
    }
    // Initialize Titan Framework.
    $titan = TitanFramework::getInstance( ‘titan-radio’ );
    // Fetch the lyrics from the options.
    $lyrics = $titan->getOption(‘my_lyrics’);
    // Make sure the lyrics are there and not empty. Else, return false.
    if ( empty( $lyrics ) ) {
        return false;
    }
    // Split the lyrics into array objects so it would be easier to randomize.
    $lyrics = explode( PHP_EOL, $lyrics );
    // Return a random line of the lyric.
    return wptexturize( $lyrics[ mt_rand( 0, count( $lyrics ) – 1 ) ] );
}
// Echo the chosen line, or a notice that you can do so.
function show_the_radio() {
    $chosen = show_radio_lyrics();
    $output = $chosen ? ‘&#9835; ‘ . $chosen . ‘ &#9835;’ : ‘Your song can go in here! Check the admin options for details!’;
    echo ‘<p id=”lyrics” style=”text-align: center;”>’ . $output . ‘</p>’;
}
// Now we set that function up to execute when the admin_notices action is called.
add_action( ‘admin_notices’, ‘show_the_radio’ );
?>​

Leave a Reply