From wordpress 3.0 version wordpress introduced the custom_post_type function. Many people want to attach the file field with add_meta_box function. In this tutorial I will tell you how to upload file with custom meta box and post type. I tested above code with new wordpress versions 3.9. Still code is working fine.

Code for File upload with meta box in wordpress using custom post type using meta boxes in wordpress.

In this tutorial I will show you how to create the custom post type and add custom meta boxes to that post type and upload file with custom meta box.

After digging into wordpress files and functions I created following code. Just open your functions.php file and put following code in that file for creating custom post type.

Some Source code is Hidden! It's Visible for Users who Liked/Shared This article on Facebook or Twitter or Google+. Like or Tweet this article to reveal the content.

For uploading the file through custom meta box use the following code. Following code will add the file field to custom meta box and you are able to upload file or image to wordpress and upload file attachment to you custom post. Following code is very helpful to many wordpress theme and plugin developer. If you are having any issues or trouble using code then get back to me.

File upload with add_meta_box or custom_post_type in wordpress File upload with meta box in wordpress

File upload with add_meta_box or custom_post_type in wordpress File upload with meta box in wordpress


<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php

 add_action("admin_init", "add_product");
 add_action('save_post', 'update_purchase_url');
 function add_product(){
 add_meta_box("product_details", "product Options", "product_options", "product", "normal", "low");
 }
 function product_options(){
 global $post;
 $custom = get_post_custom($post->ID);
 $purchase_url = $custom["purchase_url"][0];
 $product_price = $custom["product_price"][0];
 $product_image = $custom["product_image"][0];
 $video_code = $custom["video_code"][0];

?>
 <div id="product-options">
 <label>Purchase URL:</label>php echo $purchase_url; ?>" />

 <label>Product Price:</label>php echo $product_price; ?>" />

 <label>Product Image:</label>php echo $product_image; ?>" />
 <img src="<!--?php echo $product_image; ?-->">


 </div><!--end product-options-->
<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
 }
 function update_purchase_url(){
 global $post;
 update_post_meta($post->ID, "purchase_url", $_POST["purchase_url"]);
 update_post_meta($post->ID, "product_price", $_POST["product_price"]);
 update_post_meta($post->ID, "product_image", $_POST["product_image"]);

 if(!empty($_FILES['product_image']['name'])){ //New upload
 require_once( ABSPATH . 'wp-admin/includes/file.php' );
 $override['action'] = 'editpost';

 $uploaded_file = wp_handle_upload($_FILES['product_image'], $override);

 $post_id = $post->ID;
 $attachment = array(
 'post_title' => $_FILES['product_image']['name'],
 'post_content' => '',
 'post_type' => 'attachment',
 'post_parent' => $post_id,
 'post_mime_type' => $_FILES['product_image']['type'],
 'guid' => $uploaded_file['url']
 );
 // Save the data
 $id = wp_insert_attachment( $attachment,$_FILES['product_image'][ 'file' ], $post_id );
 wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $_FILES['product_image']['file'] ) );

update_post_meta($post->ID, "product_image", $uploaded_file['url']);
 }
 }
?>

For Uploading the file your post form need to add the enctype=”multipart/form-data” type to your form. Just use the following code in your functions.php file.

1

<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php
function fileupload_metabox_header(){
?>
<script type="text/javascript">
 jQuery(document).ready(function(){
 jQuery('form#post').attr('enctype','multipart/form-data');
 jQuery('form#post').attr('encoding','multipart/form-data');
 });
</script>
<!--?<span class="hiddenSpellError" pre="" data-mce-bogus="1"-->php }
add_action('admin_head', 'fileupload_metabox_header');

?>

For checking all information in edit or preview section use following code.


<?php

add_action("manage_posts_custom_column",  "product_custom_columns");
add_filter("manage_edit-product_columns", "product_edit_columns");

function product_edit_columns($columns){
 $columns = array(
 "cb" => "<input type="checkbox" />",
 "title" => "Product Title",
 "purchase_url" => "Purchase URL",
 "product_price" => "Product Price",
 "product_image" => "Product Image",
 );
 return $columns;
}
function product_custom_columns($column){
 global $post;
 switch ($column) {
 case "purchase_url":
 $custom = get_post_custom();
 echo $custom["purchase_url"][0];
 break;
 case "product_price":
 $custom = get_post_custom();
 echo $custom["product_price"][0];
 break;
 case "product_image":
 $custom = get_post_custom();
 $img_url =$custom["product_image"][0];
 echo "<image src=".$img_url." height=100 width=100 />";
 break;
 }
}

?>

File upload with meta box in wordpress

File upload with meta box in wordpress

Above code is useful for any type of customization. If you are having any issue with using this code then please get back to me.

Written by Purab Kharat

I Purab am from India, Pune. I am WordPress and Drupal Architect and consultant. I worked on many technologies like Ruby on Rails, Flex, PHP, jQuery etc... Senior Technical Lead at Smartsourcing Global Pvt Ltd in Princeton, NJ, USA.I contributed to many wordpress plugins and Drupal Modules. I contributed to Drupal core also.Connect to purab on LinkedIn or Follow @purab on Twitter or Follow me on Google+ or Write Mail to purabdk@gmail.com or Chat with me on Skype : purabdk

This article has 20 comments

  1. Zeeshan Reply

    hello,
    great code, well in my case custom fields are not displaying on the front end….

    how can i do that….thanx in advance

    • Sony Reply

      you should use the following code for displaying custom fields on front end.
      $custom = get_post_custom();
      echo $custom["CUSTOM_FIELD"][0]; // here you need to put your custom field name. that sit.

  2. desarrolloinfo Reply

    hi,

    i have a problem.

    if i use this for 1 custom post type, it’s working good.

    but i need to create other custom post type, but the image can’t be uploaded.

    thanks.

  3. Vincent Smuda Reply

    great tutorial, It really helped me learn how wordpress handles files in the backend.
    keep up the good work!

    thanks so much!!!!!

  4. Duffy Stewart Reply

    Hey Bro,
    Nice code, its helped me out a lot. Just wondering if you know how to include image_make_intermediate_size() in the function so that when you save the image it makes multiple sizes of the image like the defalt wordpress upload?

  5. rightmost Reply

    Wow, thank you! I have been looking for a solution like this for awhile. This works well for a PDF upload rather than an image upload as well. Thanks for sharing :)

  6. Swami_jeet Reply

    Pretty slick. How do you handle *multiple* file uploads with the WordPress file browser?

  7. Wordpress API Reply

    Thanks for mentioning my site. You can check wordpress related code, issues on my site. If you are having any wordpress related issues than you can ask to us.

  8. Jeremy Reply

    There doesn’t seem to be a ‘file’ index in the ‘$_FILES’ array. While this only generates a warning in PHP and allows the script to progress it does halt the progression of adding posts when the site has debugging enabled. You can use ‘name’ instead without any problems on the ‘edit post’ page but the images won’t have the correct path in ‘Media’.

    • Jeremy Reply

      In essence it should be:
      $id = wp_insert_attachment( $attachment,$uploaded_file[ 'file' ], $post_id );
      wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $uploaded_file['file'] ) );

  9. Per Reply

    Hi,

    Thanks for a great piece of code.

    I’m using this code for one of my custom post types, and each time a post is edited, it loses the image if you haven’t chosen it once again.

    My code looks like this right now:

    add_action(“admin_init”, “add_image”);
    add_action(‘save_post’, ‘update_image’);

    function add_image(){
    add_meta_box(“image_meta”, “Images”, “image_form”, “projects”, “normal”);
    }

    function image_form(){
    global $post;
    $custom = get_post_custom($post->ID);
    $product_image = $custom["product_image"][0]; ?>

    <input type="file" size="0" name="product_image" value="” />
    <a href="” target=”_blank”><img src="” width=”100″ />
    Insert x
    ID, “product_image”, $_POST["product_image"]);

    if(!empty($_FILES['product_image']['name'])){ //New upload
    require_once( ABSPATH . ‘wp-admin/includes/file.php’ );
    $override['action'] = ‘editpost';

    $uploaded_file = wp_handle_upload($_FILES['product_image'], $override);

    $post_id = $post->ID;
    $attachment = array(
    ‘post_title’ => $_FILES['product_image']['name'],
    ‘post_content’ => ”,
    ‘post_type’ => ‘attachment’,
    ‘post_parent’ => $post_id,
    ‘post_mime_type’ => $_FILES['product_image']['type'],
    ‘guid’ => $uploaded_file['url']
    );

    // Save the data
    $id = wp_insert_attachment( $attachment,$_FILES['product_image'][ 'file' ], $post_id );
    wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $_FILES['product_image']['file'] ) );

    update_post_meta($post->ID, “product_image”, $uploaded_file['url']);
    }
    }

    function fileupload_metabox_header(){ ?>

    jQuery(document).ready(function(){
    jQuery(‘form#post’).attr(‘enctype’,’multipart/form-data’);
    jQuery(‘form#post’).attr(‘encoding’,’multipart/form-data’);
    });

    <?php }

    add_action('admin_head', 'fileupload_metabox_header');

  10. Julian Reply

    As rokuta says I think this is missing the first lines of code, which is a shame as it looks EXTREMELY useful. Thanks for posting anyway

  11. chris Reply

    any chance to get the full code for this custom post type, bits are chopped off.

    thanks ;)

  12. Bill Dennen Reply

    I agree, this looks nice. But your code is cut off. Could you fix it?

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>