File upload with Custom Post Type
-
Hi
I would like to use a meta box to add a file to a post and use it as an attachment but I can’t seem to figure it out.
Currently I’m using this code:
function save_post_bijlage($post_id, $post = null) { global $post; $filename = $_FILES['bijlage']; //echo "1:" . $_FILES['bijlage']; print_r($filename); $wp_filetype = wp_check_filetype(basename($filename), null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $filename, $post_id ); // you must first include the image.php file // for the function wp_generate_attachment_metadata() to work require_once(ABSPATH . "wp-admin" . '/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $filename ); wp_update_attachment_metadata( $attach_id, $attach_data ); } add_action('save_post', 'save_post_bijlage');
and:
add_action(‘admin_menu’, ‘publicatie_meta’);
function publicatie_meta() {
add_meta_box(“publicatie_bijlage”, “Bijlage”, “meta_options”, “publicatie”, “side”, “low”);
}function meta_options() { ?> <input type="file" name="bijlage" id="bijlage"/> <?php } ?>
I can’t seem to figure out the link between getting the file uploaded to the server and attaching the attachment to the post.
I hope someone can help me out.
Thanks
-
not sure if this is the cause of your problem, but according to this blog post any attached files dont get transmitted as the standard post form doesn’t have the
enctype=”multipart/form-data”
tags. Anyway this is the post it might help.
http://www.tanzilo.com/2009/01/15/wordpress-adding-a-custom-option-box-and-developing-file-upload-plugin/Thanks
I found that post but it requires editing the core files. I’d rather not do that.
royscheeren, try this
<?php function modify_form(){ echo '<script type="text/javascript"> jQuery("#post").attr("enctype", "multipart/form-data"); </script> '; } add_action('admin_footer','modify_form'); ?>
Thnx unodj. Works like a charm.
What would be the reason it’s not there standard?
I’m trying to implement exactly the same but can’t figure out where to put which part of this code?
Look here if you want to add the media library upload to your meta box.
Using JavaScript to add the enctype is a bad idea because it won’t work for users that have JavaScript turned off or who are using devices that don’t support JavaScript. Instead, you should use the post_edit_form_tag filter, as described at http://codex.wordpress.org/Plugin_API/Filter_Reference/post_edit_form_tag.
- The topic ‘File upload with Custom Post Type’ is closed to new replies.