File upload with add_meta_box or custom_post_type in wordpress

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.

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.


<?php
 add_action('init', 'create_product');
 function create_product() {
 $product_args = array(
 'label' => __('Product'),
 'singular_label' => __('Product'),
 'public' => true,
 'show_ui' => true,
 'capability_type' => 'post',
 'hierarchical' => false,
 'rewrite' => true,
 'supports' => array('title', 'editor', 'thumbnail')
 );
 register_post_type('product',$product_args);
 }
?>

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 add_meta_box or custom_post_type in wordpress

<?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><input size="100" name="purchase_url" value="<?php echo $purchase_url; ?>" /><br>
 <label>Product Price:</label><input size="100" name="product_price" value="<?php echo $product_price; ?>" /><br>
 <label>Product Image:</label><input type="file" size="100" name="product_image" value="<?php echo $product_image; ?>" />
 <img src="<?php echo $product_image; ?>"><br>

 </div><!--end product-options-->
<?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

<?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>
<?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;
 }
}

?>

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.

You may like following Articles!

  • http://goldenapplesdesign.com Nathaniel Taintor

    Very nice. I was over-thinking this problem and making it a lot more complicated than it needs to be. This is a sweet and simple way of handling admin meta-box uploads.

    One minor thing, though… I would think that if you stored the attachment ID in the “product_image” field, rather than the absolute url of the image, you could make use of more of the built-in attachment functions.

    • http://wordpressapi.com Sony

      Thanks…I am trying to write file upload with crop and thumbnail functionality…

  • http://www.irujalikamino.com Lisa

    Hi thanks for yet another nice and interesting post. Where do you receive your inspiration for all this?

  • http://www.irujalikamino.com Laura

    Hello this post is nice and interesting. I’ll use it for my essay :). Can you tell me some related articles that I can read too?

  • http://uniline365.com MP3 Downloads

    Those post are a truly great i like them very much has a lot of great information.

  • http://freshlookcolorcontacts.net/ Rea Vaubel

    Among the a lot more amazing blogs Ive seen. Many thanks so a lot for keeping the net classy to get a alter. Youve obtained style, class, bravado. I suggest it. Make sure you maintain it up simply because without having the internet is certainly lacking in intelligence.

  • Zeeshan

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

    how can i do that….thanx in advance

    • http://wordpressapi.com Sony

      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.

  • desarrolloinfo

    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.

    • Wordpress API

      what kind of issue you are facing tell me.

  • http://www.smycze-reklamowe.info/ smycze reklamowe

    it is a really smart point of view. I usually meet people who rather say what they suppose others want to hear. Good and well written! I will come back to your site for sure!

  • http://www.mspan.co.uk/ web design edinburgh

    It is really good post, but I do not see everything completely clear, especially for someone not involved in that topic. Anyway very interesting to me.

  • http://www.GamePosts.net Doyle Baskette

    I am extremely impressed with your writing ability and also with the layout on your blog. It’s rare to see a nice site like this one these days.

  • http://www.smycz-reklamowa.pl/ smycze

    Good an very informative post. I will come back to your blog regullary. One thing: I do not exactly know what do you mean in the second paragraph. Could you please exmplain your opinion?

  • Vincent Smuda

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

    thanks so much!!!!!

  • Duffy Stewart

    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?

    • Priya Pagal

      who will answer this ? 3 years already

      • http://wordpressapi.com/ wordpressapi

        Yes, It will save in multiple sizes..

    • http://wordpressapi.com/ wordpressapi

      Yes, it will make the multiple sizes..

  • rightmost

    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 :)

    • rob

      Hey rightmost, i’m looking to use this as a pdf uploader also. Any chance you can post the full code on here as the above code seems to now be missing first lines in each panel. Thanks..

  • Swami_jeet

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

  • http://wordpressapi.com Wordpress API

    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.

  • http://jeremyhixon.com Jeremy

    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’.

    • http://jeremyhixon.com Jeremy

      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'] ) );

  • Per

    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');

  • http://www.cypressskiclub.com/user/1604 Tajuana Cruzan

    I would like to thank you for the efforts you have put in writing this blog. I’m hoping the same high-grade website post from you in the upcoming as well. In fact your creative writing abilities has encouraged me to get my own site now. Actually the blogging is spreading its wings rapidly. Your write up is a good example of it.

  • Pingback: File upload with add_meta_box or custom_post_type in wordpress « digcms

  • rokuta

    I think first few line of each code is lost?

  • http://gowebpr.com/miinsoportablesobriedad/?p=164 Fabian Fleming

    Hi there, just found your blog through Google, and located so that it is really informative. I’m gonna keep abreast of this place. Cheers!

  • http://www.attiqmas.com/apps/profile/71032207 Hermina Ruise

    You actually make it seem so easy with your presentation but I find this topic to be actually something which I think I would never understand. It seems too complex and extremely broad for me. I am looking forward for your next post, I’ll try to get the hang of it!

  • Julian

    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

  • rob

    any chance of fixing the first lines of code in each ? thanks

  • http://www.socialgamestore.co.uk Sherill Goliday

    High quality info. Keep up the great work.Very Useful blog

  • http://przeprowadzkianglia.korbofos.com/?p=3 Przeprowadzki Krakow

    Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your web site is magnificent, let alone the content!

  • http://www.michelleisapain222.com Nichelle Flannery

    You’re blogging has really come on when I look back over previous posts. Actually I arrived here from a forum on an unrelated topic. Worth surfing sometimes. Thanks.

  • http://www.daveisadave1234.com Gigi Blandin

    I just wanted to comment and say that I really enjoyed reading your blog post here. It was very informative and I also digg the way you write! Keep it up and I’ll be back to read more in the future

  • http://www.daveisadave1234.com Jesus Botting

    I don’t normally comment on blogs.. But nice post! I just bookmarked your site

  • chris

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

    thanks ;)

  • Pingback: Adding Files via a Custom Meta Box In WordPress

  • Bill Dennen

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

  • http://journeyshirts.com Gabriella Boydstun

    I’ve been checking your blog for a while now, seems like everyday I learn something new :-) Thanks

  • http://uu-skin-care.blogspot.com/ Evan Precht

    Hello, this is my first time i visit here. I found so many interesting in your blog especially on how to determine the topic. keep up the good work.

  • http://financworld.com Evan Precht

    Awesome post. I so good to see someone taking the time to share this information

  • http://best-antiaging.info Quentin Ghoston

    Great read. Thanks for the info!

  • http://back-pain-lower.info Dave Bertagna

    Good! Thank you! I always wanted to write in my site something like that. Can I take part of your post to my blog?

  • Bukaj

    Same problem here, the code doesn’t seem to be complete!

  • Pingback: File upload with meta box in wordpress | digcms