«PREVIOUS 1 2 3 4 View All NEXT»
Hello and welcome all!
In this Guide, I will show you how you can develop plugins for the brand-spankin’-new latest version of WordPress 2.7.
What are we going to develop?
A Plugin, that will add “Topic Icons” inside the content of each post.
Hasn’t this already been done before?
Yes… yes it has been. It’s called “WP Post Icon” and you can find that plugin here at Linewbie’s WordPress Plugins Page
Then why re-invent the wheel?
So, let’s begin!
Step 0. Bare-Minimum Plugin Skeleton
In this step, we will cover the following:
- 1. Creating Commented Info Block
- 2. Creating Commented License Block
First, create a blank PHP file, name it content-icons.php, with the following content:
-
<?php
-
-
/*
-
Plugin Name: Content Icons
-
Plugin URI: http://www.codingrush.com/project-release/content-icons-plugin-release
-
Description: This plugin shows 'Content Icons' within each post. It is Compatible with WordPress 2.7. I have not tested this plugin with any other version of WordPress.
-
Version: 0.1
-
Author: RushiKumar Bhatt
-
Author URI: http://www.codingrush.com
-
*/
-
-
/*
-
Copyright 2009 RushiKumar Bhatt (email : RushiKumar dot bhatt at no spam dot gmail dot com)
-
-
This program is free software; you can redistribute it and/or modify
-
it under the terms of the GNU General Public License as published by
-
the Free Software Foundation; GNU GPL version 3 of the License.
-
-
This program is distributed in the hope that it will be useful,
-
but WITHOUT ANY WARRANTY; without even the implied warranty of
-
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-
GNU General Public License for more details.
-
-
You should have received a copy of the GNU General Public License
-
along with this program; if not, write to the Free Software
-
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
-
*/
-
-
?>
Please make sure that there are no blank spaces before: <?php and after ?>. If there are any spaces, the WordPress will break, complaining that headers have already been sent.
Now, create a folder (preferably with the same name: content-icons) and place the newly-created php file inside it.
Next, upload the folder into the plugins directory:
Go to the admin area, and select “Plugins” menu option. Once there, you should see the following:

The comment block reflects what shows up in the plugins admin area
As you can see from the above snapshot, what we wrote for the comment block reflects here, in the Plugins Admin Area.
So, with our ‘bare-minimum’ skeleton out of the way, let’s make this functional, by adding key functionalities!
Step 1. Activating the Plugin
In this step, we will cover the following:
- 1. Creating Required Tables
- 2. Creating (recursively) Directory Structure to Hold our Content Icons
- 3. Adding a menu entry to the Admin Menu
- 4. Adding a “Meta Box” on the Post Page for Associating/Selecting Icons
Before we begin though, add the following block of code, right after the Warranty comment block:
-
//Define table name to use throughout our Plugin
-
global $wpdb;
-
$wpdb->cicons = $wpdb->prefix.'ci_post_ref';
-
-
//Define a term that points to the uploads folder
-
define('CICONS', ABSPATH."/wp-content/uploads/cicons");
Explanation:
The first two lines define a variable that is globally accessible for help with plugin development. As you will see, we make extensive use of this variable through out our plugin development. The next two lines deal with defining a term that points to our uploads folder–where all our images will reside.
With the content-icons.php file open, add the following code block. I am leaving the comments inside for your study.
-
/**
-
** Function: Adding "Content Icons" Meta box
-
**/
-
add_action('admin_menu', 'cicons_add_meta_box');
-
function cicons_add_meta_box() {
-
add_meta_box('ciconsdiv', __('Content Icons', 'cicons'), 'cicons_metabox_admin', 'post', 'side');
-
}
-
-
/**
-
** Function: Adding "Content Icons" menu entry to the Options Menu
-
** We are commenting out this for now, as we don't need a menu option…
-
add_action('admin_menu', 'cicons_menu');
-
function cicons_menu() {
-
if (function_exists('add_options_page')) {
-
add_options_page(__('Content Icons', 'wp-cicons'), __('Content Icons', 'wp-cicons'), 'manage_options', 'content-icons/content-icons-options.php');
-
}
-
}*/
-
-
/**
-
** Function: Content Icons Activate & Install
-
**/
-
//First, we add the action, which tells WordPress to set the activation hook for a plugin
-
//this particular call requires to parameters: the file location and name and the function name
-
//add_action('activate_content-icons/content-icons.php', 'conticons_init');
-
add_action('init', 'cicons_init');
-
function cicons_init(){
-
global $wpdb;
-
-
//let's start by defining our table name
-
$table_name = $wpdb->prefix . "ci_post_ref";
-
-
//now, we make sure that such a table doesn't already exist.
-
//if our desired table name already exist, we will not Create it again!
-
if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
-
//we will be creating a table that holds two key pieces of information: icon id, and the post it belongs to.
-
$create_cicons_info = "CREATE TABLE " . $table_name . " (
-
`post_id` INT NOT NULL ,
-
`icon_name` TEXT NOT NULL ,
-
PRIMARY KEY ( `post_id` )
-
);";
-
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
-
dbDelta($create_cicons_info);
-
}
-
-
//create the upload directory
-
wp_mkdir_p(ABSPATH."/wp-content/uploads/cicons");
-
}
Explanation:
Lines 38 - 41, overall, we are adding meta box to the write post page. More specifically though: On line 40, we are using the add_meta_box WordPress Function–which was introduced in WordPress v2.5–to add a section to the Write Post page.
Lines 46 - 51, achieve the task of adding a menu entry of Content Icons. However, as mentioned in the code, we are going to comment it out for now as we really don’t need a menu entry for this Plugin just yet…. I have kept this code as-is in the above code block for two reasons:
- 1. Show you how to add menu entries and
- 2. Save me some typing for future version
![]()
In the next block, we are using dbDelta function of WordPress in order to create the required table where we will store our information.
Lastly, On line 80, we are using yet another WordPress built-in function to create our upload directory structure. This is a very useful function as it simply takes the desired path and recursively creates the structure.
Well, there you have it. We are all done with Step 1. However, do not try and activate the plugin just yet… as WordPress would throw a fit (and rightfully so, as we have yet to define a function cicons_metabox_admin() that we have called when we created the meta box!… that is saved for the next step.)
Step 2. Adding Functionality
In this step, we will cover the following:
- 1. Meta Box Function
- 2. Fetching all the Images from the Uploads Directory and Displaying them in Select Box
- 3. Preview Functionality (Preview Selected Icon)
- 4. If Content Icon Exist for the Post, Show it.
Within the content-icons.php file, right after the cicons_init() function, copy/paste the following block.
-
/**
-
** Function: Meta Box Function
-
**/
-
function cicons_metabox_admin() {
-
global $wpdb, $post;
-
$currentPID = $post->ID;
-
echo '
-
<h3 class="dbx-handle"> Selection </h3>
-
<h4 class="dbx-handle">Select Icon to Associate With This Post — ID '.$currentPID.'</h4>
-
<div class="dbx-content">
-
<p>
-
<select id="select_icon" name="select_icon" onChange="icon_preview.src=(\''.cicons_url().''.get_upload_path().'/\'+this.options[this.selectedIndex].value);">';
-
-
//let's proceed only if the post id exist — this ensures that we don't make unneccessary queries to our database
-
if($currentPID != null){
-
//echo 'not null';
-
$chkIfExist = $wpdb->get_results("SELECT icon_name FROM `$wpdb->cicons` WHERE `post_id` = $currentPID AND `icon_name` != ''");
-
}
-
-
//if we have already associated a content icon to the post, let's display
-
//that image's name first (instead of the non-sensical "Select Icon…" text)
-
if($chkIfExist){
-
$imagename = $chkIfExist[0]->icon_name;
-
//we are going to padd the select box with some blank spaces… just so it doesn't look all crammed up!
-
echo '<option value="'.$imagename.'">'.$imagename.' </option>';
-
//if have yet to associate a content icon to the post, we will
-
//let the author select know to select one…
-
}else{
-
echo '<option value="">Select Icon … </option>';
-
}
-
//let's display the rest of the icons that we find in our upload directory
-
if ($dir = opendir(CICONS)) {
-
while(false !== ($file = readdir($dir))) {
-
if ($file != '.' && $file != '..') {
-
$extension = strtolower(substr($file, strrpos($file, '.')+1));
-
if ($extension === 'jpg' || $extension === 'jpeg' || $extension === 'gif' || $extension === 'png') {
-
echo '<option value="' . $file . '">' . $file . ' </option>' . "\n";
-
}
-
}
-
}
-
closedir($dir);
-
}
-
-
echo '
-
</select>
-
</p>
-
</div>
-
-
<h3 class="dbx-handle"> Preview </h3>
-
<div class="dbx-content">
-
<br />
-
<center><img id="icon_preview" src="'. cicons_url().''.$icon.'" /></center>
-
<br />
-
</div>';
-
-
//Adding functionality: Displaying current selected content icon for the post at hand (i.e., for the current post)
-
if ($chkIfExist) {
-
//echo 'found a match…<br />';
-
echo '<h3 class="dbx-handle"> Current Selection</h3>
-
<div class="dbx-content">
-
<br />
-
<center><img id="curr_icon_preview" src="'. cicons_url().''.get_upload_path().'/'.$chkIfExist[0]->icon_name.'" /></center>
-
<br />
-
</div>';
-
}
-
}
-
-
/**
-
** Function: Get the site's url
-
**/
-
function cicons_url() {
-
$url = trailingslashit(get_option('siteurl')) . $def_path;
-
return $url;
-
}
-
-
/**
-
** Function: Get the Upload Path
-
**/
-
function get_upload_path(){
-
$path = str_replace(ABSPATH, '', get_option('upload_path')."/cicons");
-
return $path;
-
}
Explanation:
Lines 86 - 148, overall, is our meta-box function. This block of code is responsible for showing everything that appears on the write post page. I will briefly point out the highlights of this code block: we first check to see if the post already has associated an icon with itself (line 99). If it has, then we will use this information to drive our design/display of the select box (lines 104 - 109). Next, we display all our icons (jpg, jpeg, gif, or png files) that are located within the uploads directory (lines 114 - 124). As we mentioned above, the check we make to see if the icon already exist for the given post, we use the same check to base our “Current Selection” block on. If the author has yet to assign an icon, we don’t even bother with showing the Current Selection div/block.
The last two function, cicons_url() and get_upload_path() are pretty self-explanatory. The former deals with getting the site’s URL and the latter function fetches the upload directory path.
At this point, what you have is
- a plugin that can be activated/deactivated
- if activated, you have a dropdown select box in the post page that fetches all the icons from the uploads directory
- dynamically preview selected icon
- display current icon associated with the post (if it exist)
We are almost there! 85% done!
Next, we put on some finishing touches for our FIRST version of the plugin…beta version that is :p
Step 3. Finishing Touches…
In this step, we will cover the following:
- 1. SAVE: Saving the Information to the Database
- 2. DELETE: Delete Record, Upon Deletion of Post
- 3. DISPLAY: Display the Icon for Each Post Content
Within our content-icons.php file, at the end of the last code block that we entered, copy and paste the following code block:
-
/**
-
** Function: Save our information whenever we save or publish the post
-
**/
-
add_action('save_post', 'add_cicons_admin_process');
-
function add_cicons_admin_process($post_ID) {
-
global $wpdb;
-
-
$cPID = wp_is_post_revision($post_ID);
-
if($cPID != null){
-
$select_icon = $_POST['select_icon'];
-
// Ensure No Duplicate Field
-
$check = intval($wpdb->get_var("SELECT * FROM `$wpdb->cicons` WHERE `post_id` = $cPID"));
-
if($check == 0) {
-
$wpdb->query( "INSERT INTO $wpdb->cicons (post_id, icon_name) VALUES ($cPID, '".$select_icon."')" );
-
} else {
-
if($select_icon != null){
-
$wpdb->query( "UPDATE $wpdb->cicons SET icon_name = '".$select_icon."' WHERE post_id = $cPID" );
-
}
-
}
-
}
-
}
-
-
/**
-
** Function: Delete the content icon associated with the post when the post itself gets deleted
-
**/
-
add_action('delete_post', 'delete_cicons_process');
-
function delete_cicons_process($post_ID) {
-
global $wpdb;
-
-
$cPID = wp_is_post_revision($post_ID);
-
if($cPID != null){
-
-
// Only proceed further if the content icon exist
-
$check = intval($wpdb->get_var("SELECT * FROM `$wpdb->cicons` WHERE `post_id` = $cPID"));
-
if($check > 0) {
-
$wpdb->query( "DELETE FROM $wpdb->cicons WHERE post_id = $cPID" );
-
}
-
}
-
}
-
-
/**
-
** Function: Display our content icon within the post/the content itself
-
**/
-
function display_content_icon($post_content){
-
global $wpdb, $post;
-
if($post->ID != null){
-
// Only proceed further if the content icon exist for the post
-
$chkIfExist = $wpdb->get_results("SELECT icon_name FROM `$wpdb->cicons` WHERE `post_id` = $post->ID");
-
if($chkIfExist) {
-
$imageStr = '<img id="content_icon" src="'. cicons_url().''.get_upload_path().'/'.$chkIfExist[0]->icon_name.'" align="right" style="padding: 5px" />';
-
$post_content = $imageStr . $post_content;
-
}
-
}
-
return $post_content;
-
}
-
//we need to tell word press to pass the content THROUGH our function… so we can append content icon to the post
-
add_filter('the_content', 'display_content_icon');
Explanation:
On line 170, we are telling wordpress, “Look brother, whenever a user of this system tries to save/update the post, include my function as well…. please“. That being said, The function that follows, is the one that will be invoked when wordpress is saving a post (lines 171 - 187).
The most important line in this block, or so I feel that way, is line 173: This line basically employs WordPress’s built in function to get the ACTUAL PostID as oppose to the ridiculous and unimportant RevisionID. This is important because otherwise, we would be making absurd number of database inserts/updates queries (especially if the author is like me, who writes a long post, and in the background WordPress keeps creating auto-save entries…)
Similarly, On line 192, we are telling wordpress to call our function when a user tries to delete a post. The function that follows (lines 193 - 205) basically checks to see if we have a database table entry containing the current post’s ID (ID of the post that is to be deleted) as one of the records. If it does, the function deletes the record. We don’t need it, once the post is deleted… so why keep the record around?
Finally, On line 223, we are telling wordpress that whenever it is showing content, pass the whole content through our function (lines 210 - 221), so that we can add the icon that is associated with a particular post.
And there you have it! Save the file, upload/overwrite existing content-icons.php file, activate it and start playing around with it. Remeber, upload all your icons inside the “ROOT/wp-content/uploads/cicons/” folder! (this folder should be created for you once you activated the Plugin from the Admin area)
Furthermore, I have not walked-through each line of code in this Guide, as I feel that I have done enough explanation after each code block AS WELL AS in-line commenting. However, if you are unsure of something, please do ask.
Questions? Comments? Critiques? Features Request
Please direct all your questions/comments/critiques/feature requests at the CodingRush.com site–which is the official site for this Plugin, as also the official site of all my future works. GuidesForge is simply just that: a site that hosts (mainly) my tutorials, how-tos, and step-by-step guides (among other services).
Suggestions etc. For This Step-by-Step Guide
However, if you have any suggestions/improvements/ or would like to add to the explanation of the code or this guide in general, than please use the comments section below.
Finally:
I hope you enjoyed this step-by-step guide as much as I did writing it! (Not to mention all the frustration that I went through in order to make this Plugin). Really though, you must write one yourself in order to get the true joy! So, if you believe in assignments, your next assignment is to write a plugin (even if its something that has already been done before)… it could be a simple one, or you can just go wild and run with an idea… whatever the case maybe, have fun doing it, as that’s all it matters.
Credits:
No work would be properly “complete” until/unless the credits are given where they are due. So here we go–
First and Foremost, the Author of WP Post-Icon, Linewbie. Next to the Author of WP-Sticky, Mr. Lester Chan and finally to the Author of Category Icons, Mr. Sadish Bala for help with coding. (I used their plugins’ code as a reference from point-to-point)
Enjoy!
Popularity: 100% [?]
Posted by
Under
Tags: 
5 Comments Received
January 22nd, 2009 @5:38 am
Hi! A good forum, glad to join you
October 22nd, 2009 @2:29 am
Hi i read your code. It is very understandable way. But am getting error after activating this plugin.
Error: we cannot change the headers……
April 4th, 2010 @8:21 am
Hi Madhu,
Please provide more information. What version of WP are you running? Which file is it mentioning? Can you quote the error (Copy & Paste) ?
Pingback & Trackback
Leave A Reply