Upload an Image Using WordPress Custom Field

We use WordPress custom field to enter more information on a post or a page. But sometimes the project demands to have other features such as image, video, audio, etc. And your clients are not familiar with adding HTML image tags or video URL.

The solution is enable them to upload a file or an image using custom field. I’m lucky to found this script and I made some minor adjustment so it’s easier to understand by beginners.

To get started, copy the code below and paste it in functions.php file of your template:

// image custom field

if ( is_admin() ) {
    function add_post_enctype() {
        echo "<script type='text/javascript'>
                  jQuery(document).ready(function(){
                      jQuery('#post').attr('enctype','multipart/form-data');
                  });
              </script>";
    }
    add_action('admin_head', 'add_post_enctype');
}

$new_meta_boxes =
array(

"start" => array(
"name" => "start",
"type" => "start"),

//Banner Custom Fields

"banner" => array(
"name" => "big_banner",
"std" => "",
"type" => "image",
"title" => "Big Banner 790x60"), 

"smallbanner" => array(
"name" => "small_banner",
"std" => "",
"type" => "image",
"title" => "Small Banner 250x250"), 

"end" => array(
"name" => "end",
"type" => "end"),
);

function new_meta_boxes() {
global $post, $new_meta_boxes;

foreach($new_meta_boxes as $meta_box) {
$meta_box_value = get_post_meta($post->ID, $meta_box['name'].'', true);

if($meta_box_value == "")
$meta_box_value = $meta_box['std'];

echo'<input type="hidden" name="'.$meta_box['name'].'_noncename" id="'.$meta_box['name'].'_noncename" value="'.wp_create_nonce( plugin_basename(__FILE__) ).'" />';
if($meta_box['type'] == "start") {

echo "<div class='optionsbox'><style type='text/css'>.optionsbox {
display:block;
width:auto;
float:none;
overflow: hidden;
}

.optionsbox input, .optionsbox textarea {
outline:none;
padding:5px;
color:#999;
}

.optionsbox input:focus, .optionsbox textarea:focus {
border-color:#999;
color:#666;
}

.optionsbox p {
margin-bottom:20px;
}

.optionsbox label {
width:140px;
display:block;
float:left;
margin-top:3px;
}

.optionsbox small {
padding-left:140px;
padding-top:3px;
color:#999;
}
</style>";

} else if($meta_box['type'] == "end") { 

	echo '</div>';

} else if($meta_box['type'] == "image") { 

	echo $meta_box['before'];

	echo '<div style="background:#f4f4f4;padding:10px;height:120px;margin:0 0 20px 0;display:block">';

	if($meta_box_value) { echo '<img style="float:right" src="'.get_bloginfo('template_directory').'/scripts/timthumb.php?src='.$meta_box_value.'&w=120&h=120" alt="" />'; }

	echo'<p><label for="'.$meta_box['name'].'_upload">'.$meta_box['title'].'</label>';
	echo'<input type="file" name="'.$meta_box['name'].'_upload" size="55" /><br />';
	echo'<small>Upload image here</small></p>';

	echo'<p><label> </label>';
	echo'<input type="text" name="'.$meta_box['name'].'" value="'.$meta_box_value.'" size="55" /><br />';
	echo'<small>or add a URL to the image here</small></p>';

	echo '</div>';

} else if($meta_box['type'] == "text") { 

	echo $meta_box['before'];

	echo'<p style="margin-bottom:20px;"><label style="width:140px;display:block;float:left;margin-top:3px;" for="'.$meta_box['name'].'">'.$meta_box['title'].'</label>';
	echo'<input style="color:#666;" type="text" name="'.$meta_box['name'].'" value="'.$meta_box_value.'" size="55" /><br />';
	echo'<small style="padding-left:140px;padding-top:3px;">'.$meta_box['description'].'</small></p>';

} else if($meta_box['type'] == "checkbox") { 

	echo $meta_box['before'];

	echo'<p style="margin-bottom:20px;"><label style="width:140px;display:block;float:left;margin-top:3px;" for="'.$meta_box['name'].'">'.$meta_box['title'].'</label>';
	if($meta_box_value) { $checked = "checked=\"checked\""; } else { $checked = ""; }
	echo '<input style="display:block;float:left;width:20px;margin:5px 0 0 0;" '.$checked.' type="checkbox" name="'.$meta_box['name'].'" /><br/>';
	echo'<small style="clear:both;padding-left:140px;padding-top:3px;display:block;">'.$meta_box['description'].'</small></p>';

} else if($meta_box['type'] == "textarea") { 

	echo $meta_box['before'];
	echo'<p style="margin-bottom:20px;"><label style="width:140px;display:block;float:left;margin-top:3px;" for="'.$meta_box['name'].'">'.$meta_box['title'].'</label>';
	echo'<textarea style="color:#666;" name="'.$meta_box['name'].'" cols="50" rows="4">'.stripslashes($meta_box_value).'</textarea><br />';
	echo'<small style="padding-left:140px;padding-top:3px;">'.$meta_box['description'].'</small></p>';

} 

}
}

function create_meta_box() {
global $theme_name;
if ( function_exists('add_meta_box') ) {
add_meta_box( 'new-meta-boxes', 'Custom Fields (Upload Banner Images)', 'new_meta_boxes', 'post', 'normal', 'high' );
}
}

function save_postdata( $post_id ) {
global $post, $new_meta_boxes;
$post_id = wp_is_post_revision($post_id);

foreach($new_meta_boxes as $meta_box) {

	if ( !wp_verify_nonce( $_POST[$meta_box['name'].'_noncename'], plugin_basename(__FILE__) )) {
	return $post_id;
	}

	if ( 'page' == $_POST['post_type'] ) {
	if ( !current_user_can( 'edit_page', $post_id ))
	return $post_id;
	} else {
	if ( !current_user_can( 'edit_post', $post_id ))
	return $post_id;
	}

$imageuploadlocation = "";
$metaboxname = "";
$metaboxname_upload = "";

if($meta_box['type'] == 'image') {

	$metaboxname = $meta_box['name'];
	$metaboxname_upload = $metaboxname.'_upload';

	if($_FILES[$metaboxname_upload]['name'] != "") {
		$overrides = array( 'test_form' => false);
		$imagefile=wp_handle_upload($_FILES[$metaboxname_upload], $overrides);
		$imageuploadlocation = $imagefile['url'];
		delete_post_meta($post_id, $metaboxname, get_post_meta($post_id, $metaboxname, true));
		add_post_meta($post_id, $metaboxname, $imageuploadlocation, true);
	} else {
		$imageuploadlocation = get_post_meta($post_id, $metaboxname, true);
		delete_post_meta($post_id, $metaboxname, get_post_meta($post_id, $metaboxname, true));
		add_post_meta($post_id, $metaboxname, $_POST[$metaboxname], true);
	} 

} else {

	$data = $_POST[$meta_box['name'].''];
	if(get_post_meta($post_id, $meta_box['name'].'') == "")
	add_post_meta($post_id, $meta_box['name'].'', $data, true);
	elseif($data != get_post_meta($post_id, $meta_box['name'].'', true))
	update_post_meta($post_id, $meta_box['name'].'', $data);
	elseif($data == "")
	delete_post_meta($post_id, $meta_box['name'].'', get_post_meta($post_id, $meta_box['name'].'', true));

}

}

}

add_action('admin_menu', 'create_meta_box');
add_action('save_post', 'save_postdata', 12);
// end of image custom field

Yeah you’re right, it’s a bit long. If you want you may put it in a different file and just use require or include commands if possible.

Also, see these lines:

The yellow highlighted text will be the title of new custom field. See the image below:

The green highlighted text are the custom field names that you use in the post or page template. To know more about getting the value of the custom field name you can read How to Get WordPress Custom Field Value.

Now, the user have two options in adding an image. To upload an image or enter the image URL where uploading image is a lot easier.

*Some links may contain affiliate links. I may get small commission from your purchases to fund this website and to avoid annoying ads.