WordPress: adding a custom option box and developing file upload plugin
Hello Buddy,
One of my clients wanted to show thumbnail photo beside the post text as below. So, I had to make a plugin so that the admin can post the thumbnail when he is writing the post or can edit when editing the post. Take a look at the thumbnail’s position below.
Thus, recently I solved a plugin problem in one of my wordpress works although it was small. You know you may sometimes need to add a custom field in your wordpress posting/writing/editing area. To check what I am saying, take a look at the following image:
Adding such a box is extremely easy using the wordpress’s builtin add_meta function. But does file upload works i.e. if you upload the file, will it work? The answer is straight – “NO”. But why? The reason is also simple. If you want to upload a file, your form should have “enctype=”multipart/form-data” in the form opening such as
<form name="post" action="post.php" method="post" id="post" enctype="multipart/form-data">
But the problem is – if you open the source code of text editor tool as following,
you will see that it does not have “enctype=”multipart/form-data” unfortunately. It looks exactly like this in my wordpress 2.7 version if I open the wp-admin/edit-form-advanced.php file at line # 520.
<form name="post" action="post.php" method="post" id="post">
Not funny? Huh?
So, to cope up with this situation, I had to add “enctype=”multipart/form-data” in the form although I do not like changing the core files. Why do not I like to change the core files? The answer simple. Because whenever there is an update, the client have to update the file everytime. The client may not like it or may even forget it. Anyway, after change, it looks like this:
<form name="post" action="post.php" method="post" id="post" enctype="multipart/form-data">
OK. Lemme show you step by step what to do if you want to add a file upload plugin.
Step One: Change the “wp-admin/edit-form-advanced.php” file
Open this file from the mentioned location and change the following line in the file:
<form name="post" action="post.php" method="post" id="post">
to this line:
<form name="post" action="post.php" method="post" id="post" enctype="multipart/form-data">
Step Two: Write you plugin
Here goes mine:
<?php /* Plugin Name: Bag Thumbnail Plugin URI: http://www.tanzilo.com/ Description: This plugin helps you to set thumbnail image of your bags. Author: Tanzil Al Gazmir Version: 1.0 Author URI: http://www.tanzilo.com/ */ function init_bag_review_thumb_widget() { global $wpdb; $result = mysql_list_tables(DB_NAME); $current_table = array(); while($row = mysql_fetch_row($result)) { $current_tables[] = $row[0]; } $myNewDatabaseTable = $wpdb->prefix . 'bag_thumb'; if(!in_array($myNewDatabaseTable, $current_tables)) { mysql_query(" CREATE TABLE IF NOT EXISTS `" . $myNewDatabaseTable . "` ( `id` int(11) NOT NULL auto_increment, `post_id` int(11) NOT NULL, `image_name` varchar(255) NOT NULL, PRIMARY KEY (`id`) ); "); } /* // Now I am going to delete all unnecessary thumb images by scanning the // whole directory */ $sqlQuery = "SELECT image_name FROM " .$wpdb->prefix . "bag_thumb; "; $fileArray = $wpdb->get_col($sqlQuery); $fileArray[] = 'no_thumb.jpg'; if ($handle = opendir('../bag_thumb/')) { // This is the correct way to loop over the directory. while (false !== ($file = readdir($handle))) { if(is_file('../bag_thumb/' . $file)) { if(!in_array($file, $fileArray)) { unlink('../bag_thumb/' . $file); } } } closedir($handle); } } // This function tells WP to add a new "meta box" function add_bag_photo_box() { add_meta_box( 'bag_photo', // id of the <div> we'll add 'Add Bag Thumbnail Photo', //title 'add_bag_photo', // callback function that will echo the box content 'post', // where to add the box: on "post", "page", or "link" page 'normal', 'high' ); } // This function echoes the content of our meta box function add_bag_photo() { echo '<label> Select a thumbnail (150px by 100px) photo for this bag<br /> <input type="file" name="bag_thumbnail_photo" id="bag_thumbnail_photo" /> </label> <input name="bag_thumbnail_set" type="hidden" id="bag_thumbnail_set" value="yes" /> '; } function bag_thumbnail_plugin_save_postdata() { $fileArray = array(); global $wpdb; $file = $_FILES['bag_thumbnail_photo']; $fileName = $_FILES['bag_thumbnail_photo']['name']; $basename = ''; if(!empty($fileName)) { if(isAllowedExtension($_FILES['bag_thumbnail_photo']['name'])) { $postID = $_POST['post_ID']; # Do uploading here $basename = basename( $_FILES['bag_thumbnail_photo']['name']); $basename = str_replace(' ', '_', $basename); $basename = str_replace('-', '_', $basename); $basename = strtolower($basename); $basename = $_POST['post_ID'] . '_' . $basename; $target_path = '../bag_thumb/'; $target_path = $target_path . $basename; $sqlQuery = "DELETE FROM " . $wpdb->prefix . "bag_thumb WHERE post_id=$postID;"; $wpdb->query($sqlQuery); move_uploaded_file($_FILES['bag_thumbnail_photo']['tmp_name'], $target_path); // adding record in the database $sqlQuery = "INSERT INTO " . $wpdb->prefix . "bag_thumb(post_id, image_name) VALUES($postID, '$basename')"; $wpdb->query($sqlQuery); } } } function isAllowedExtension($fileName) { $allowedExtensions = array("png", "gif", "jpg", 'jpeg'); return in_array(end(explode(".", $fileName)), $allowedExtensions); } // This starts whenever the plugin is loaded add_action("plugins_loaded", "init_bag_review_thumb_widget"); // Hook things in, late enough so that add_meta_box() is defined if (is_admin()) { /* Use the admin_menu action to define the custom boxes */ add_action('admin_menu', 'add_bag_photo_box'); } /* Use the save_post action to do something with the data entered */ add_action('save_post', 'bag_thumbnail_plugin_save_postdata'); ?>
Please notice that I dynamically delete any unnecessary file using the PHP’s unlink() function.
Step Three: get your image name from the database
I have placed the following code in my functions.php file.
<?php if(!function_exists('getBagThumbName')) { function getBagThumbName($postID) { global $wpdb; $sqlQuery = 'SELECT image_name FROM ' . $wpdb->prefix . 'bag_thumb WHERE post_id=' . $postID . ';'; $fileName = $wpdb->get_var($sqlQuery); $fileName = trim($fileName); $fileURL = get_option('siteurl') . '/bag_thumb/' . $fileName; if(!empty($fileName)) { return $fileURL; } else { return (get_option('siteurl') . '/bag_thumb/no_thumb.jpg'); } } } ?>
Step Four: Link with the index.php or single.php or wherever you want
See how I placed the thumbnail image source in the code of index.php and single.php file.
<div id="singlePostAdRight"> <a href="#postContentAnchor"><img src="<?php global $post; echo getBagThumbName($post->ID); ?>" class="singlePostThumb" border="0" /></a> </div>
Step Five: Test
Now you need to test and we are done!
You can also download my little plugin if you want from here:
http://www.tanzilo.com/demo/code/bag-thumb/bag-thumb.zip
Thank you for reading.







