News

Create a custom WordPress author plug-in

Create a WordPress plugin to display author details using best coding practices

Plugin

WordPress plug-ins are a great way to add extended functionality to your blog. They simplify complicated functions for users, allowing them to add additional features through shortcodes or widgets. The overall installation of a WordPress plug-in is straightforward, but what happens in the background can change the entire way WordPress functions.

We will not cover adding plug-in elements manually to a theme file as this is a very manual process. This tutorial has best practices in mind, and shows you how to store data correctly, and more importantly, how to remove all traces of your plug-in when it is deactivated. Although removing all data when a plug-in is removed is not a requirement of a plug-in that is released to the community, it is generally wise to make sure you do so to avoid clogging up the WordPress database with information that is not needed and hard to remove.

This tutorial assumes that you have a hosting environment set up, running the latest version of PHP and MySQL. It also assumes that you are running the latest version of WordPress. If you are not, it may be worth upgrading before you proceed through the admin section of your site.

DOWNLOAD TUTORIAL FILES

Getting started

The first thing you need to think about when creating a WordPress plug-in is file naming. Your file names need to be completely unique. This is so they do not conflict with any other plug-ins another user may already have installed on the server from a third party. For this tutorial it is best that you develop on a clean WordPress install.

Creating a document

Open Dreamweaver – or your text editor of choice – and create a new PHP file. Add the following opening and closing tags to the document. Now save it with the name ‘authorinfo.php’ to the wp-content/plugins/ folder of your clean WordPress install.

001 <?php
002
003 ?>

Adding plug-in information

The following block of code will need to be added to our newly-created PHP file. This code has all been commented out, so in theory it should not be useful in any way whatsoever. However, WordPress uses this commented section to determine some key information about our plug-in. We will cover the GPL3 licence in the next step.

001 <?php
002 /*
003 Plugin Name: Author Box WD201
004 Plugin URI: http:// [Your plugin website 
here]
005 Description: Add an author box to your blog
006 Version: 1.0
007 Author: [Your Name]
008 Author URI: http:// [Your website here]
009 License: GPL3
010 */
011 ?>

GPL3 Licence

Underneath your comment code, add the following statement. This is customary content for a plug-in header, and good practice if you want to release your plug-ins to the rest of the WordPress community. The GPL3 license is a general public license that allows everyone to copy and distribute your work. Do not use this licence if you want to sell your plug-in.

001 /* Copyright (C) 2012 [Your Name]
002 
003    This program is free software: you can 
redistribute it and/or modify
004    it under the terms of the GNU General 
Public License as published by
005    the Free Software Foundation, either 
version 3 of the License, or
006    (at your option) any later version.
007 
008    This program is distributed in the hope that it will be useful,
009    but WITHOUT ANY WARRANTY; without even 
the implied warranty of
010    MERCHANTABILITY or FITNESS FOR A 
PARTICULAR PURPOSE.  See the
011    GNU General Public License for more 
details.
012
013    You should have received a copy of the 
GNU General Public License
014    along with this program.  If not, see 
<http://www.gnu.org/licenses/>.
015 */
016 

Verify your plug-in

At this stage it is worth doing a quick check within WordPress to make sure that your plug-in information is being loaded correctly. Once you have updated your PHP file in the Plugin folder of WordPress, navigate to the Plugin menu within your WordPress admin section. If all has worked, you should see your plug-in listed.

Adding settings

Before we can add functionality, it is worth getting everything we need set up. Under your licence comment, add the following code. This code will create a menu item for your plug-in, in the Settings tab of the admin section of WordPress. The author-box-settings is the name of the string that appears in the address bar.

001 add_action( 'admin_menu', 'authorbox_menu' );
002 
003 function authorbox_menu() {
004    add_options_page( 'AuthorBox Options', 
'Author Box', 'manage_options', ‘author-box-
settings’, 'authorbox_options' );
005 }

Settings output


Add the following function underneath the previous step. This will display some basic HTML in our settings page. Over the next step we will code a form for users to fill out information about the author of the blog. The previous step references this function when it adds the menu item so it is important that you ensure there are no spelling mistakes.

001 function authorbox_options() {
002    if ( !current_user_can( 'manage_options' ) )  {
003        wp_die( __( 'You do not have sufficient 
permissions to access this page.' ) );
004    }
005    echo '<div>';
006    echo '<p>We'll build a form here, 
promise!</p>';
007    echo '</div>';
008 }

Settings page titles

Replace our placeholder echo statements from the previous step with the following code. You can see the <h2> tag is coded slightly differently to a standard tag. The reason for this is that the titles can relate to multiple settings tabs and it is good practice to learn how to code this way.

001 echo ‘<div class=”wrap”>’;
002    echo “<h2>” . __( ‘Author Box Plugin 
Settings’, ‘author-menu’ ) . “</h2>”;
003 ?>

Adding a form

The next step is to add our form that will allow us to input our author information. You will notice that the PHP tag was closed in the last step, we will now add a standard HTML form with the below code.

001 <form name="form1" method="post" 
action="">
002 <input type="hidden" name="<?php echo 
$hidden_field_name; ?>" value="Y">
003
004 <p><?php _e("Author's Name:", 'author-menu' ); ?> 
005 <input type="text" name="<?php echo $data_
field_name; ?>" value="<?php echo $opt_val_
name; ?>" size="20">
006 </p>
007 <p><?php _e("Author's Bio:", 'author-menu' ); ?> <br />
008 <textarea name="<?php echo $data_field_bio; ?>" cols="80" rows="8"><?php echo $opt_val_bio; ?></textarea>
009 </p>
010 <p><?php _e("Author's Picture:", 'author-
menu' ); ?> 
011 <input name="<?php echo $data_field_image; ?& gt;" type="file" />
012 </p>
013 <hr />
014
015 <p>
016 <input type="submit" name="Submit" 
class="button-
primary" value="<?php esc_attr_e('Save 
Changes') ?>" 
/>
017 </p>
018
019 </form>
020 </div>
021 
022 <?php
023 
024 } ?>

Adding form variables

As you will notice from the previous step, we have added PHP variables in our form that make up both the input name and value. In between your die statement and your <dive class=”warp”> element, place the following few lines of code. This code will set all the variables for the form name and values. If the values are set these will be overwritten.

001 $opt_name = 'author_box_name';
002    $opt_bio = 'author_box_bio';
003    $opt_image = 'author_box_image';
004       $hidden_field_name = 'mt_submit_hidden';
005        $data_field_name = 'author_box_name';
006    $data_field_name_bio = 'author_box_bio';
007    $data_field_name_image = 'author_box_
image';

Adding database options


The following code will set up a new set of database fields in your WordPress options table. The register_activation_hook function only calls this function when the plug-in is activated for the first time. Add this code under your header section, and activate the plug-in to see the results in your database, by viewing the last three rows of the wp_options table.

001 function author_install() { 
002   add_option( ‘name’, ‘’, ‘’, ‘yes’ );
003   add_option( ‘bio’, ‘’, ‘’, ‘yes’ );
004   add_option( ‘image’, ‘’, ‘’, ‘yes’ );
005 }
006 
007 register_activation_hook(__FILE__,’author_
install’);

Getting existing options

If you submit your options form now, you will notice your wp_options table updates. However, the values are not being pulled into the form. This leaves you with blank fields when the page reloads, after the form is submitted. Add the following code before your if statement within your authorbox_options function.

001 $opt_val_name = get_option('author_box_
name');
002     $opt_val_bio = get_option('author_box_
bio');
003    $opt_val_image = get_option('author_box_
image');                

Handling image uploads

You may have noticed that our image upload element doesn’t really do much at the moment, apart from add the filename to the database. Add this code within your if statement. The code will check to ensure that a user is only uploading an image – nothing else – it also adds a size limitation; change this to whatever you need it to be.

001 $allowedExts = array(“jpg”, “jpeg”, “gif”, “png”);
002        $extension = end(explode(“.”, $_
FILES[$data_field_image][“name”]));
003        if ((($_FILES[$data_field_image][“type”] == “image/gif”)
004        || ($_FILES[$data_field_image][“type”] 
== “image/jpeg”)
005        || ($_FILES[$data_field_image][“type”] 
== “image/pjpeg”))
006        && ($_FILES[$data_field_image][“size”] < 200000)
007        && in_array($extension, $allowedExts))
008          {
009          if ($_FILES[“file”][“error”] > 0)
010            {
011                echo “Error: “ . $_FILES[$data_
field_image][“error”] . “<br />”;
012            }

013          else

014            {    
015                $upload_dir = wp_upload_dir();
016                  move_uploaded_file($_FILES[$data_
field_image][“tmp_name”], $upload_
dir[‘basedir’] . “\” . $_FILES[$data_field_
image][“name”]);
017            }
018          }

019        else

020          {
021                echo “Invalid file”;
022          }

Fixing some errors

As we’ve changed the way the code handles files, we now need to go ahead and update our form and update_option values. You should update your form with the following line; this will allow us to upload the actual image data – in whatever file format it may be in – rather than just take the filename from the form. You can also delete the $opt_val_image variable from within the if statement.


001 <form name=”form1” method=”post” action=”” 
enctype=”multipart/form-data”>

Image in database

If you now submit your form with an image, you will see the image appear in the wp-content/uploads folder. If you don’t see it there, you may need to create the uploads folder and set permissions to 777. You
also need to update the final update_option command to the following code – this code will add the full image path to the database.

001 update_option( $opt_image, $upload_
dir['baseurl'] . "/" . $_FILES[$data_
field_image]["name"] );

Displaying an image

It would be a good idea to display the image within the settings page to provide some feedback when the form is submitted. You need to add this code within your form, updating the image upload field. This if statement will then pull the URL from the database – if there is one set.

001 <p><?php _e("Author's Picture:", 'author-
menu' ); ?> <br />
002 <?php if ($opt_val_image != '') { ?>
003    <img src="<?php echo get_option($opt_
image); ?>" />
004    <p>Update image
005 <?php } ?> 
006 <input name="<?php echo $data_field_image; 
?>" type="file" />
007 </p></p>

Adding a sidebar


Now we have our options page completed, we can start on making the plug-in output something to the front end of our site. The easiest way to do this would be to add the option to display the information in a sidebar. Add the following code to the bottom of your PHP to generate the sidebar output.

001 function your_widget_display($args) {
002   extract($args);
003   echo $before_widget;
004   echo $before_title . 'About the Author' . $after_title;
005   echo '<img src="'.get_option('author_box_
image').'" style="max-width:150px" /><br />';
006   echo    '<strong>'.get_option('author_box_
name').'</strong>';
007   echo '<p>'.get_option('author_box_
bio').'</p>';
008   echo $after_widget;
009 }                            

Register the sidebar

Now we have the code to display the output of the sidebar, we need to register it with WordPress. Adding the following code under the previous step will add the sidebar into the Widgets section of the WordPress admin. You can now drag the widget onto a sidebar and see the results.

001 wp_register_<
br /> sidebar_widget(
002    ‘author_box_
widget’,        
003    ‘Author Box’,          
004    ‘your_widget_display’,  
005    array(                  
006        ‘description’ => ‘Display 
information about the blog author in your 
sidebar’
007    )
008 );

Adding shortcodes


Shortcodes are an easy way to place an element within a blog post. This element is normally driven by a plug-in or theme. Adding the following code under the previous step will allow users to add author information anywhere in a post by simply typing “[authorbox]”. You can change the style of this as you see fit.

001 function author_shortcode($atts){
002    return ‘<strong>About the Author</
strong><br /><img src=”’.get_option(‘author_
box_image’).’” style=”max-width:150px” /><br 
/><strong>’.get_option(‘author_box_name’).’</
strong><p>’.get_option(‘author_box_bio’).’</
p>’;
003 }
add_shortcode( 
‘authorbox’, ‘author_
shortcode’ );

Auto redirecting

Currently the user journey is very messy. They activate the plug-in, then visit the Settings page to add author information, manually. We want to redirect them to our settings page as soon as they hit activate on the Plugin screen. Scroll to the top of your code and add replace your author_install function with this one and an additional function.

001 function author_install() { 
add_option( ‘author_box_name’, ‘’, ‘’, ‘yes’
);
002   add_option( ‘author_box_bio’, ‘’, ‘’, 
‘yes’ );
003   add_option( ‘author_box_image’, ‘’, ‘’, 
‘yes’ );
004   add_option(‘activation_redirect’, true);
005 }

006 function plugin_redirect() {
007    if (get_option(‘activation_redirect’, 
false)) {
008        delete_option(‘activation_
redirect’);
009        $adminUrl = admin_url();
010        wp_redirect($adminUrl.’/options-
general.php?page=author-box-settings’);
011    }
012 }

Activate the redirect


Now it’s time to call our redirect function and see it in action. Add the following line underneath our register_activation_hook command. Now if you go to the Plugins page in your admin section, deactivate, and then reactivate the plug-in, you will be automatically taken to the Settings page. You will also notice our old data is still present.

001 add_action('admin_init', 'plugin_
redirect');

Cleaning up


From the previous step, you will notice that our old data was left behind once we deactivated our plug-in, this isn’t great as it clogs up the WordPress database. Adding the following code will delete our plug-in data on deactivation. Add this underneath your activation hook to keep things neat.

001 function author_deactivate() { 
002   delete_option( ‘author_box_name’, ‘’, 
‘’, ‘yes’ );
003   delete_option( ‘author_box_bio’, ‘’, ‘’, 
‘yes’ );
004   delete_option( ‘author_box_image’, ‘’, 
‘’, ‘yes’ );
005 }
006
007 register_deactivation_hook( __FILE__, 
‘author_deactivate’ );

AUTHOR: Pete Simmons

×