I am just learning to create a meta box to upload a file in wp-content/uploads folder through this code:
//display image meta box
function display_image_box() {
global $post;
wp_nonce_field( plugin_basename( __FILE__ ), 'wp_custom_noncename' );
echo '<input id="post_media" type="file" name="post_media" value="" size="25" />';
}
//upload image
function update_custom_meta_data( $id, $data_key, $is_file = false ) {
if( $is_file && ! empty( $_FILES ) ) {
$upload = wp_handle_upload( $_FILES[$data_key], array( 'test_form' => false ) );
if( isset( $upload['error'] ) && '0' != $upload['error'] ) {
wp_die( 'There was an error uploading your file. ' );
} else {
update_post_meta( $id, $data_key, $upload );
}
}
}
//save image
function save_custom_meta_data( $id ) {
if( ! wp_verify_nonce( $_POST['wp_custom_noncename'], plugin_basename( __FILE__ ) ) ) {
return;
}
if( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return;
}
update_custom_meta_data( $id, 'post_media', true );
}
add_action( 'save_post', 'save_custom_meta_data' );
//register script
function register_admin_scripts() {
wp_register_script( 'custom_admin_script', get_template_directory_uri() . '/js/admin.js' );
wp_enqueue_script( 'custom_admin_script' );
}
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
This is working and the file uploads nicely but I can't display it because I'm getting an array like this:
[post_media] => Array
(
[0] => a:3:{s:4:"file";s:81:"E:wampwwwtestchild/wp-content/themes/twentyeleven/uploads/2012/12/coffee_star.jpg";s:3:"url";s:60:"wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg";s:4:"type";s:10:"image/jpeg";}
)
How can I display the image in my template?
In addition, how to save the URL ( wp-content/themes/twentyeleven/image/2012/12/coffee_star.jpg ) only as meta data?