SIC Digital Blog

We make things for the internet and we love it.

How to Create a Custom Post Type with Image Uploads For WordPress 3

I’ve been working on a project to create a CMS for a series of dental websites. One of the important things is to be able to make the CMS as simple as possible for the end users, so I’ve set out using WordPress 3′s new custom post types to create and display these nice and neat. For this example I wanted to create a post type for “Before and After” images. Rather than having the end user have to go to media, upload it, and then grab the link for the page I wanted to have them to be able to go in to a “Before and After” post type and simply upload1 upload2 and press publish. Here’s how I went about doing it.

Step 1 : Create the Custom Post type

Custom post types are pretty easy to create:

// Creates before and after post type
add_action('init', 'post_type_before_after');
function post_type_before_after() 
{
  $labels = array(
    'name' => _x('Before and Afters', 'post type general name'),
    'singular_name' => _x('Before and After', 'post type singular name'),
    'add_new' => _x('Add New', 'before_and_after'),
    'add_new_item' => __('Add New Before and After')

  );
 
 $args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true, 
    'query_var' => true,
    'rewrite' => true,
    'capability_type' => 'post',
    'hierarchical' => true,
    'menu_position' => null,
    'supports' => array('title','excerpt')); 
  
  register_post_type('before_and_after',$args);
  
} 

Step 2: Creating the meta boxes

The custom post type above if you look at the code

 'supports' => array('title','excerpt')); 

What this does is tell WordPress what stuff you want on the admin page. I only want the title and excerpt fields on mine because I’m going to add some extras. You could also add, “editor”,
comments” etc..

 'my-meta-box',
	'title' => 'Before and Afters',
	'page' => 'before_and_after',
	'context' => 'normal',
	'priority' => 'high',
	'fields' => array(
		array(
			'name' => 'Before',
			'desc' => 'Select a Before Image',
			'id' => 'upload_image',
			'type' => 'text',
			'std' => ''
		),
				array(
			'name' => '',
			'desc' => 'Select an After Image',
			'id' => 'upload_image_button',
			'type' => 'button',
			'std' => 'Browse'
		),
	array(
			'name' => 'After',
			'desc' => 'Select an After Image',
			'id' => 'upload_image2',
			'type' => 'text',
			'std' => ''
		),
	array(
			'name' => '',
			'desc' => '',
			'id' => 'upload_image_button2',
			'type' => 'button',
			'std' => 'Browse'
		),
	)
);

add_action('admin_menu', 'mytheme_add_box');

// Add meta box
function mytheme_add_box() {
	global $meta_box;
	
	add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']);
}

// Callback function to show fields in meta box
function mytheme_show_box() {
	global $meta_box, $post;
	
	// Use nonce for verification
	echo '';
	
	echo '';

	foreach ($meta_box['fields'] as $field) {
		// get current post meta data
		$meta = get_post_meta($post->ID, $field['id'], true);
		
		echo '',
				'',
				'';
	}
	
	echo '
'; switch ($field['type']) { //If Text case 'text': echo '', '
', $field['desc']; break; //If Text Area case 'textarea': echo '', '
', $field['desc']; break; //If Button case 'button': echo ''; break; } echo '
', '
'; } add_action('save_post', 'mytheme_save_data'); // Save data from meta box function mytheme_save_data($post_id) { global $meta_box; // verify nonce if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } // check permissions if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } foreach ($meta_box['fields'] as $field) { $old = get_post_meta($post_id, $field['id'], true); $new = $_POST[$field['id']]; if ($new && $new != $old) { update_post_meta($post_id, $field['id'], $new); } elseif ('' == $new && $old) { delete_post_meta($post_id, $field['id'], $old); } } } function my_admin_scripts() { wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); wp_register_script('my-upload', get_bloginfo('template_url') . '/functions/my-script.js', array('jquery','media-upload','thickbox')); wp_enqueue_script('my-upload'); } function my_admin_styles() { wp_enqueue_style('thickbox'); } add_action('admin_print_scripts', 'my_admin_scripts'); add_action('admin_print_styles', 'my_admin_styles');

Ok so what this has done is write all of the meta box fields that you want. The php reads what you put in the array and all of those switch cases check to see what kind of input field it is then create the format accordingly. You can copy and paste that exactly as is and it will work for this tutorial.

This should leave you with

Step 3: Getting the WordPress Media Upload working for the browse buttons

So now we have the meta boxes for the custom field but what we want is the end user to be able to click browse and upload an image or select from the gallery. Just for usability sake you know? Heres how we do it.

If you look at the code above

 function my_admin_scripts() {
wp_enqueue_script('media-upload');
wp_enqueue_script('thickbox');
wp_register_script('my-upload', get_bloginfo('template_url') . '/functions/my-script.js', array('jquery','media-upload','thickbox'));
wp_enqueue_script('my-upload');
}
function my_admin_styles() {
wp_enqueue_style('thickbox');
}
add_action('admin_print_scripts', 'my_admin_scripts');
add_action('admin_print_styles', 'my_admin_styles');

This loads the wp_enqueue_script(‘thickbox;), as well as registers the “my-upload” function which will be used to link to some jquery that adds functionality to our browse buttons.

Step 4: The Jquery for the Browse Buttons

jQuery(document).ready(function() {

jQuery('#upload_image_button').click(function() {
											  window.send_to_editor = function(html) {
 imgurl = jQuery('img',html).attr('src');
 jQuery('#upload_image').val(imgurl);
 tb_remove();


}


 tb_show('', 'media-upload.php?post_id=1&type=image&TB_iframe=true');
 return false;
});


});

jQuery(document).ready(function() {

jQuery('#upload_image_button2').click(function() {
											   window.send_to_editor = function(html) {
 imgurl = jQuery('img',html).attr('src');
 jQuery('#upload_image2').val(imgurl);
 tb_remove();

 
}

 tb_show('', 'media-upload.php?post_id=1&type=image&TB_iframe=true');
 return false;
});



});

Want to learn more WordPress?

This book is way worth checking out if your just getting in to WordPress. Chris Coyier is awesome and this book is a great place to start.

About the Author

MichaelMichael is a WordPress developer and speaker based out of Miami Beach, FL.View all posts by Michael →

  1. LeviLevi07-28-2010

    Thanks for a very informative post.

    Though I think you forgot to list where to add the function code.

    Cheers

  2. adminadmin07-28-2010

    everything goes in the functions file, step 4 is in a separate .js file though.

  3. chugschugs08-03-2010

    I have been trying to implement this code.
    I am having trouble with the image upload function. I am able to create the meta box with the browse button and the upload box also pops up. But on clicking on the “Insert into post” link, nothing happens.
    I was wondering what the expected result should be and if you could give any inputs on what might be going wrong.

    PS – I am able to save whatever I copy/paste into the meta box.

  4. adminadmin08-03-2010

    Hey Chugs,
    Is the image uploading fine? Do you see what you select in your media gallery? If so it is a problem with the javascript portion.

    jQuery('#upload_image').val(imgurl);

    make sure “#upload_image” is the ID of the text input field of your image. If you look at the array in Step2

    'id' => 'upload_image',
    

    this is where the ID is defined. Basically the jquery is looking for ID upload_image text box to paste to when you click on “Apply To Post”.
    Of course you can name this whatever you want.

    'id' => 'anything-goes-here'

    works as long as the Jquery is also changed to

    jQuery('#anything-goes-here').val(imgurl);
  5. chugschugs08-04-2010

    No the image doesn’t get uploaded into the media gallery.
    A copy/pasted value gets saved though.

    Am posting my functions.php code and the js file code here –
    http://pastebin.com/qht5azXS

  6. mkjonesmkjones10-22-2010

    Hey Michael,

    I’m not getting the ‘Insert Into Post’ button on the upload. The images are going up just fine, they appear in the media library and as a gallery if you add more than 1.

    At first I though this was at fault in the JS:


    tb_show('', 'media-upload.php?post_id=1&type=image&TB_iframe=true');

    What with ‘post_id’ equalling ’1′ but after hacking around that it still doesn’t seem to work.

    Any ideas?

  7. MichaelMichael10-23-2010

    hey Kimb, I’m going to have a look at this on Monday and probably rewrite and package it up for download. If you haven’t found you’re solution check back and I can help you out, could even be as early as tomorrow. :)

  8. HalHal10-26-2010

    Hey, this all works for me just fine! Thanks. But one issue, the images get uploaded fine, they are in the media gallery, etc, but they have no post_parent value (is always ’0′, so there seems to be no way to retrieve them later from the theme. How does that association work? Is there some mechanism other than post_parent to know which item is the attachment of which post? Is there a way to set this explicitly somewhere that I am missing. Thanks, again!

  9. jeanbasketjeanbasket10-27-2010

    Hi,
    Just the topics i was lokking for.
    Please, where do you put the js script?

  10. MichaelMichael11-01-2010

    the javascript goes in to /functions folder in your theme.

  11. MichaelMichael11-01-2010

    the association is stored in the posts meta if you need the code to output this let me know

  12. MichaelMichael11-01-2010

    if you go in to “Show” on the right hand side the insert in to post is at the bottom, it’s hard to see if you have lots of images in your library.

  13. anveranver11-02-2010

    Same problem as “chugs” everything works fine except the image url is not getting pasted into the textbox after clicking the “insert into post” button inside the media upload window. I just copied and pasted everything exactly as in this page. Any help is appreciated.
    Thanks.

  14. MichaelMichael11-04-2010
    window.send_to_editor = function(html) {
     imgurl = jQuery('img',html).attr('src');
     jQuery('#upload_image').val(imgurl);

    this is where your image upload is posted to the box. make sure your text box is the same id (#upload_image for this example)

  15. ConorConor11-06-2010

    Thanks for this code man, great help! Much appreciated :)

  16. MichaelMichael11-07-2010

    no problem, glad to help.

  17. chrischris11-10-2010

    could anyone please explain how one could define a custom template for the media uploader.

    All i want to do is have the browse button show a list of all the files within the media library BUT I would like to have each media library elements with the optional fields of category & tags… I would then just like to define (filter) the list of available media library elements based on specific categories and/or tags. In other words, if the media does not have a category of “XXX” and/or tag(s) of “YYY” then the browse button media list will not show the media within the library if the browse button is clicked.

    Any help would be greatly appreciated.

  18. PaulPaul11-10-2010

    I solved the problem that chugs and anver were having where nothing would happen when they clicked, “Insert into post”.

    Replace this line:
    imgurl = jQuery(‘img’,html).attr(‘src’);

    With this:
    imgurl = jQuery(html).attr(‘src’);

    Or this:
    imgurl = jQuery(html).attr(‘src’) || jQuery(html).find(‘img’).attr(‘src’) || jQuery(html).attr(‘href’);

  19. PaulPaul11-10-2010

    Here is the full code:


    jQuery(document).ready(function(){

    jQuery('#banner_image_button').click(function() {
    window.send_to_editor = function(html) {
    //imgurl = jQuery('img', html).attr('src');
    imgurl = jQuery(html).attr('src');// || jQuery(html).find('img').attr('src') || jQuery(html).attr('href');
    jQuery('#banner_image').val(imgurl);
    //alert(imgurl);
    tb_remove();
    }
    tb_show('', 'media-upload.php?post_id=1&type=image&TB_iframe=true');
    return false;
    });

    });

  20. BethBeth11-12-2010

    Having trouble pulling this into my template, could someone please post an example of how to output this? Thank you!!

  21. BethBeth11-12-2010

    Ah never mind, I was over complicating this:

    echo get_post_meta($post->ID, 'upload_image', true);

  22. MarkMark12-03-2010

    You rock! I spent all day trying to get this to work with a ton of other blogs and tutorials. So close… I nearly gave up. Literally, I was shutting down for the day and decided to make one last search.

    This works perfectly. As is. No edits. THANK YOU!

  23. Ron S. DoyleRon S. Doyle12-07-2010

    Thanks so much for the excellent tutorial. I’ve been through 3 or 4 others with no success—yours is the only one that worked!

    I thought I’d share my solution for adding different file types, specifically PDF:

    Change these two lines:
    imgurl = jQuery('img',html).attr('src');
    jQuery('#upload_image').val(imgurl);

    To this:
    fileurl = jQuery(html).attr('href');
    jQuery('#upload_pdf').val(fileurl);

  24. Ron S. DoyleRon S. Doyle12-07-2010

    Oh, and naturally the #upload_pdf is a reference to a different ID… ;-)

  25. MarcMarc12-09-2010

    I have copied and pasted all of the code as is; everything seems to work, but when I preview the draft I do not see any pictures.

    I could really really use help on this. Thanks!

  26. clintclint12-13-2010

    i’ve been looking for an upload box like this for days!
    works great!!! THANKS!!

    i do have one question, and it’s just a matter of style and not functionality … but is there a way that i can use just the plain ‘ole “browse for file” method like i’d use on a normal form (as opposed to the fancy thickbox uploader). I’d rather the clients just hit the browse button, then select their file (thus skipping the “insert into post” step)

  27. BethBeth12-20-2010

    For those wondering how to attach to the correct post, this is what I came up with:

    postid = jQuery('#post-id').val();
    tb_show('', 'media-upload.php?post_id=' + postid + '&type=image&TB_iframe=true')

    where #post-id is a hidden input field with the post id for a value.

    In my case, post id #1 doesn’t exist anymore…

  28. TewonawongaTewonawonga12-22-2010

    I’m having two issues:

    1) Every single image uploaded for this custom post type appears on the Gallery tab. When I check the Media Library, I see that all the images are incorrectly associated with the same post.

    2) I’ve implemented this on three sites already (yay!). The “Insert into Post” button does not appear on one of them (boo!). Any ideas?

  29. brunobruno01-06-2011

    Great article. With this code, the post is saved, only if you put a title. Usually, the posts in WordPress are saved if you not put a title. Best regards.

  30. John ChandlerJohn Chandler01-12-2011

    Michael,
    This is a fantastic write-up. Thanks. I have one suggestion, and one question.

    Suggestion:
    I’m using this with a child theme, so I had to change the wp_register_script line from get_bloginfo(‘template_url’) to get_bloginfo(‘stylesheet_directory’) for it to properly find my .js file. Might be worth changing that in your post for others using a child theme?

    Question:
    Like Tewonawonga above, the “Insert into Post” link is also not appearing for me at the bottom of the uploader. Any suggestions?

  31. MichaelMichael01-12-2011

    thanks, I’ll check it out. I found out for some reason .gif images don’t give the “Insert in to Post”, is it a .gif you’re testing with?

  32. MichaelMichael01-12-2011

    thanks :)

  33. MichaelMichael01-12-2011

    the images are stored as meta data in the draft, so the preview you would be viewing would need to have the meta echoed out or you wouldnt see anything. If you still need help come back and I can show you what to do.

  34. John ChandlerJohn Chandler01-13-2011

    I’m not using a .gif. I’ve tested with a .jpg. Ultimately, I want to use a .pdf, and also tried it with the suggestion mentioned in the comments above for a .pdf, but it’s the same result either way.

    The “Use as Featured Image” and “Delete” links appear, but not the “Insert Into Post”…

  35. JasonJason01-13-2011

    I loved this tutorial as well. Much time saved. I really appreciate it, but I’m also having trouble making the “Insert into post” option appear. I tried the solution suggested by Paul, but that didn’t work for me.

    Same as John Chandler, I’m not using a .gif and I do get the “Use as Featured Image” and “Delete” links.

  36. JasonJason01-13-2011

    Actually, I just noticed that on a new upload, the insert to post link is there, it’s just not there if I’m trying to use something that’s already in the media library. . .

  37. John ChandlerJohn Chandler01-13-2011

    Jason,
    You’re a step ahead of me…I don’t have that “Insert into post” option in any of the tabs.

  38. Ben BormanBen Borman01-14-2011

    +1 On the “Insert Into Post” bug – The button is not showing. I would greatly appreciate a fix, as this is an immensely useful function!

  39. JasonJason01-16-2011

    Hmm. . .Not sure what the bug could be.

    I did find this tutorial though, which seems to have some similar information on creating the upload option. . .

    http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/

  40. Ben BormanBen Borman01-18-2011

    @Jason Thanks for the link. So after some tinkering, I have it working, but in the opposite way that you mentioned above – When I do a new upload, the Insert button does not appear. If I switch to the Media Library tab and choose an image, I can select an image and Insert Into Post from there. It’s an extra step for the end user, but at least I have functionality during development…

  41. 3emeOeil3emeOeil01-19-2011

    Thanks for this great tutorial.
    Everything works fine for me except for
    the echo get_post_meta($post->ID, ‘upload_image’, true); witch display the url of the meta box content and not the image.
    How can i fix that?
    Thanks @Ron S Chandler for the pdf trick and the @john Chandler for the child theme one
    What about a word file?

  42. 3emeOeil3emeOeil01-20-2011

    ok i found out for the echo with :
    <a href="ID, ‘upload_pdf’, $single = true); ?>”…

    How can i add a doc type now?
    Thanks for your help

  43. Ron S. DoyleRon S. Doyle01-22-2011

    Thanks for the replies, Michael. Awesome tutorial.

    I’m uploading PNGs, GIFs, PDFs, etc. They all have the same problem.

    Want to know something even stranger? I’m using this media uploader script for multiple clients and getting different results on each. Sometimes it works fine, other times it doesn’t. Weird, eh?

  44. Jaki LevyJaki Levy02-05-2011

    This is a really solid tutorial – nice work, here and solid documentation.

    For people looking for other tutorials / references , check out this tutorial on ThinkVitamin – I found this post a pretty useful guide as well : http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/

  45. Towfiq I.Towfiq I.02-06-2011

    I found a fix for the “insert into post” button disappearing.
    Change this code:
    postid = jQuery(‘#post-id’).val();
    tb_show(”, ‘media-upload.php?post_id=’ + postid + ‘&type=image&TB_iframe=true’)

    To

    postid = jQuery(‘#post-id’).val();
    tb_show(”, ‘media-upload.php?post_id=’ + 1 + ‘&type=image&TB_iframe=true’)

    I know it is not the best way but at-least it works :(

  46. FredrikFredrik02-12-2011

    Hello,

    I assume that you should put the first block of code first, the second block under the first and the third under the second block of code in function.php

    Allthough I get a error message when doing this. Can you please add a complete description of all the code together without divided up in three different like it is now?

    / Fredrik

  47. MelindaMelinda02-15-2011

    I am having the same problem with the “Insert into Post” button. It doesn’t show up. Any ideas how to fix this?

  48. RyanRyan02-16-2011

    Melinda, I tried Towfiq’s solution but it didn’t work for me. The only way I’ve been able to get around this is with a CORE hack which is obviously a last resort as it will have to be re-done every time you update WP.

    If you just need it to work though you can change line 1267 in:
    wp-admin/includes/media.php

    from ($send) to (!$send) and ta-da! Hopefully that will get updated in a later release but for now its all that I’ve found that works consistently.

  49. MichaelMichael02-22-2011

    Hey everybody, so the reason you probably aren’t getting the “Insert Into Post” is because the editor is disabled on your custom post type. I had to revisit this today and so far I have it working if when you register the post type you include the editor

    ‘supports’ => array(‘title’,’excerpt’,’editor’));

  50. MelindaMelinda02-22-2011

    I now have the Insert into post working. How do I add the meta box to another custom post type (‘page’ => ‘portslider’,)? Can I add one to another custom post type for example ‘mycustomposttype2′?

  51. MichaelMichael02-23-2011

    You would add a whole new meta box for that page. Including a whole new array in $metabox

    array(
    'id' => 'my-meta-box2',
    'title' => 'something_else',
    'page' => 'some_other_page...',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(......etc)

  52. Sup3rnautSup3rnaut03-13-2011

    I get this working for one custom post type, but trying to add it to another one doesnt work for me using the code above. Does $meta_box need to have an array inside to hold the individual pages e.g
    $meta_box = array(
    $meta_box01 = array(
    ‘id’ => ‘my-meta-box’,
    ‘title’ => ‘something_else’,
    ‘page’ => ‘some_other_page…’,
    ‘context’ => ‘normal’,
    ‘priority’ => ‘high’,
    ‘fields’ => array(……etc)

  53. MichaelMichael03-13-2011

    yes, every page you want a new metabox on you should add a new array inside the meta_box array. like you have $meta_box01, then you would have $meta_box02, etc..

  54. FoomagooFoomagoo03-15-2011

    Works like a charm!

  55. MichaelMichael03-18-2011

    glad I could help :)

  56. Bobby AdamsonBobby Adamson03-22-2011

    Where do you put the javascript code? I’m a n00b

  57. Bobby AdamsonBobby Adamson03-22-2011

    Sorry, figured it out! Would you mind maybe editing your original post with the answers to some of the questions people have posted in the comments? Thanks for the awesome plugin!

  58. Kym Van ArsdaleKym Van Arsdale03-31-2011

    Great tutorial. Got it working and it is sweet! Thanks so much.

    For everyone having problems with the Insert into Post button coming up, I was also having this issue. I finally created a hidden input in my HTML and made the value equal to the post id. Then in the JavaScript, I used HTML DOM to look up the value of the hidden input and replaced the post_id=1 portion of the media URL with the actual post id. Worked like a charm.

    I also got it to accept pdfs using jQuery(html).attr(‘href’); instead of jQuery(‘img’,html).attr(‘src’);

  59. ToddTodd04-20-2011

    Cheers for this, it helped a lot!

  60. MichaelMichael04-20-2011

    Glad to hear it!

  61. Thanks a million for documenting this, very very handy… however I found that the images uploaded fine to the media library but were not attached to the post in question. Does anyone have a fix for this?Thanks!

  62. Kyle NewsomeKyle Newsome05-09-2011

    Works fantastic! Thanks so much for posting this.

    One small issue that @Kym Van Arsdale noticed, is that you are attaching the image to post # 1 a.k.a “Hello World” in your ‘tb_show()’ . This doesn’t seem to affect the upload/post type association but it isn’t exactly correct either. Inputting the correct post_id seems to create no image attachement association, which is better than nothing.

  63. Roger FRoger F05-24-2011

    You’re the man! Thanks for sharing.

  64. MichaelMichael05-26-2011

    thanks. Glad to help.

  65. IngmarIngmar06-06-2011

    Hi,
    is there any way to create a option field? I’ve tried to add this to the function.php file:


    case 'selectyear':
    echo '
    Jaar 1
    Jaar 2
    ',
    '', $field['desc'];
    break;

    But this will automatically add option 2 to the custom field.

    Suggestions anybody?

    Thnx

  66. IngmarIngmar06-06-2011

    I’m sorry, I don’t have much experience questioning on blogs. So I’ve just used the ‘code’ tags to put my code into, but I see that’s not working.

    My code again:

    //If Select Year option list
    case ‘selectyear’:
    echo ‘
    Jaar 1
    Jaar 2
    ‘,
    ”, $field['desc'];
    break;

  67. IngmarIngmar06-06-2011

    no that’s not working either..
    anyway, any help is really appriciated!

  68. AnthonyAnthony06-11-2011

    I am still having a problem with the “Insert to Post” button not showing up.

    I have tried all the suggestions in the comments, and also my Custom Post has an editor.

    Was there any other solutions for this?

  69. Giri dharGiri dhar06-17-2011

    Awesome tutorial. I think it would be nice if you give the source code as downloadable files. :)

  70. adamadam06-18-2011

    hi – this is great thx so much.

    i am having trouble when i hit publish on the created page – i get a blank screen. i am working locally though, would this make any difference?

  71. JasonJason06-26-2011

    Fantastic post!!!!! – with this it’s now easy to turn the back-end of WordPress into a highly customized CMS (especially great for less tech-saavy clients who won’t have to mess around with using special categories to mark the News vs Case Studies vs Articles posts.

    The next step would be to turn this all into an admin function on a theme so you could create new custom posts directly via the theme’s admin area. If I get anywhere on this I’ll post up some code ;-)

  72. JasonJason06-26-2011

    Drat. I can’t seem to get a second custom post type working. Trying to insert the second meta_box in the array as per the comments above, but I don’t think I’m modifying the calls correctly to attach them to the new custom post type (what’s happening it I’m getting the second post type but without any of the custom fields I added).

    Would someone mind posting a snipping of their functions.php code which does this? Much appreciated!!!!

  73. ZyrqZyrq07-06-2011

    Great writeup and it works flawlessly, thanks for this!
    I have one question though.
    When I output the image I can only get the original size as ‘inserted in post’
    get_post_meta($post->ID, ‘upload_image’, true)

    The other sizes are in the uploads folder, how can I use these?
    Ideally I would like to insert the thumb size with a link to the original size.
    Any ideas? thanks!

  74. MonclerMoncler07-13-2011

    thanks for you share with us, I think it would be nice if you give the source code as downloadable files.

  75. watermelonkidwatermelonkid08-10-2011

    Like Anthony and some of the others, I cannot get the Insert into Post link to show up despite following all the advice here. I’m trying to use this as a PDF uploader, and I’ve made the appropriate changes to the jQuery for that–but no dice! Anyone able to point in the right direction or share your solution if you too are using it as a PDF loader! Many thanks!

  76. ThomasThomas08-12-2011

    Works great. You’re the man Michael. My only thing which is odd is when I click “Update” to finalize it it takes me to a white screen at http://wp.localhost/wp-admin/post.php

    Thoughts?

  77. ThomasThomas08-12-2011

    Nevermind. I removed a couple of the items I didn’t need in the array and it worked. Strange doings! Thanks ;-)

  78. watermelonkidwatermelonkid08-15-2011

    Anyone have a code sample using this to upload PDFs? Been through this 3 times, and still can’t the Insert into Post link to appear. Appreciate any help or guidance if anyone has this working with PDFs.

    permadusk@gmail.com

  79. Zean DesignZean Design08-17-2011

    watermelonkid, si trabaja para PDFs

    Code my-script.js

    jQuery(document).ready(function() {
    jQuery(‘#upload_image_button’).click(function() {
    formfield = jQuery(‘#upload_image’).attr(‘name’);
    tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);
    return false;
    });
    window.send_to_editor = function(html) {
    //imgurl = jQuery(‘img’,html).attr(‘src’); //image
    imgurl = jQuery(html).attr(‘href’); //others
    jQuery(‘#upload_image’).val(imgurl);
    tb_remove();
    }
    });

  80. GavinGavin08-22-2011

    This was very useful, thank you for the documentation. I do believe I am the developer that inherited this code :)…

  81. JuliJuli08-23-2011

    Amazing tutorial, Thanks a lot.
    I have a small problem, I want to add a checked or select, one of this two will be great.

    I have added the checked like this, but it doesn’t work, any help will be apreciated, thanks.

    // If Checked
    case 'checked':
    echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" />',

    '<br />', $field['desc'];
    break;

  82. JuliJuli08-23-2011

    After a few minuts, solucion resolved, if someone need this:

    // If checkbox
    case 'checkbox':
    echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />',

    '<br />', $field['desc'];
    break;

    Thanks one more time!

  83. I have a small problem, I want to add a checked or select, one of this two will be great.

    I have added the checked like this, but it doesn’t work, any help will be apreciated, thanks.

    // If Checked
    case ‘checked’:
    echo ”,

    ”, $field['desc'];
    break;

  84. The North FaceThe North Face09-15-2011

    Alice the North Face’s effortlessly recognizable emblem, which is composed of three concentrically scaled-down quarter-circles, is an interpretation of the famed Half Dome rock formation in Yosemite National Park.The North Confront expanded in the 1980′s to to create a line of excessive skiwear, and by the conclude of the decade they had become the only supplier in the U.S.

  85. JeffJeff09-29-2011

    This post was a life saver. I have everything working perfectly right now, except one thing. How do I add this to all post types? I tried adding an array to the page option, but it doesn’t work right in an array.

    $meta_box = array(

    ‘id’ => ‘featured-meta-box’,
    ‘title’ => ‘Feature This on the Homepage Slider?’,
    ‘page’ => array( ‘post_service’, ‘post’, ‘page’)
    ‘context’ => ‘normal’,
    ‘priority’ => ‘high’,
    ‘fields’ => array(

    Any ideas?

  86. Lee MasonLee Mason10-17-2011

    I found a solution to the “insert into post” button bug.

    the solution is a bit sub optimal as it means the images arent attached to the post (but are still uploaded and the values will fill in the text areas on the meta boxes). it just means when viewing the media area you wont see the post id attached to the images (small price to pay for working script).

    simply change this:

    tb_show(”, ‘media-upload.php?post_id=1&type=image&TB_iframe=true’);

    to this:

    tb_show(”, ‘media-upload.php?type=image&TB_iframe=true’);

  87. MonclerMoncler10-26-2011

    Today ,i look this article i find that it is a good .YOU are so great.

  88. onyouonyou10-26-2011

    Thanks for posting this tutorial!

    Obviously there is a problem with the “insert into post” button when trying to attach media without the editor. A very simple solution is to hide the editor instead of disable it:

    function my_post_type_head(){
    if (get_post_type()==”your_post_type”){
    echo ” .postarea{display:none} “;
    }
    }
    add_action(“admin_head”,”my_post_type_head”);

    Hope this helps someone!

  89. intricatesoundsystemsintricatesoundsystems10-31-2011

    where exactly does the jquery / javascript code go?

  90. Design CollectorDesign Collector11-09-2011

    Great article! Thanks for writing the tutorial. It works preperly!

  91. NSMENSME11-18-2011

    Hello,

    Nice tutorial, but i´ve got a problem with the jQuery script… when i´m create a new Post, my Buttons doesn´t work… Includepath:

    Scriptpath
    wp-content/plugins/plugin_name/functions/my-script.js

    php file path
    wp-content/plugins/plugin_name/beforeafter.php

  92. sebastiensebastien11-30-2011

    Hi, i want to change the folder for the images uploaded with this uploader.
    How can i do this ?

  93. Payer en lignePayer en ligne12-05-2011

    Hello, I’m very happy to have found this script, thanks a lot… but i don’t know how to display images on post now…! I know i’m not good developer .. Could you help me please?

  94. Sorry i found the answer… it was in the first section of your comments…! You are the man thanks for this trick !

  95. MichaelMichael12-20-2011

    You’re welcome

  96. MichaelMichael12-20-2011

    The URL’s of the images are stored as post meta. Check http://codex.wordpress.org/Function_Reference/get_post_meta, to see how to pull the value of the post meta fields. Let me know if that helps.

  97. MichaelMichael12-20-2011

    They should be uploaded to your default uploads folder. You can change your default upload folder in the settings of your WP site. Settings -> Media

  98. MichaelMichael12-20-2011

    You’re welcome.

  99. tylertyler12-27-2011

    Reformatted the Javascript to be more readable and flexible.

    jQuery(document).ready(function() {
    //when user clicks button or text input, we launch the code.
    jQuery(‘div.inside input:button, div.inside input:text’).click(function() {
    //grab the input name info.
    var title = jQuery(this).attr(‘id’);
    var image_id = title.replace(“_button”, “”);

    window.send_to_editor = function(html) {
    imgurl = jQuery(‘img’,html).attr(‘src’);
    jQuery(“#” + image_id).val(imgurl);
    tb_remove();
    }

    tb_show(”, ‘media-upload.php?post_id=1&type=image&TB_iframe=true’);

    return false;
    });

    });

  100. davidedavide01-03-2012

    first of all thank you for this tutorial, it seems the only one on the web that seems to work.

    @Tyler Your script looks very clever but it doesn’t work for me, did you tested it?

    by the way I still don’t know how to show the uploaded images inside the post, do someone know how to display it?

    thank you

  101. sereneserene01-16-2012

    thanks for this great tut!

    one question: i have made a single select box type and works great.

    but what about multiple select, and checkbox? it does not return all selected values, only the last one selected.
    any tips on these without involving javascript? i have jquery method but i would not use that if it can be avoided.

    thanks!

  102. sereneserene01-17-2012

    figured it out :)

  103. Victor HugoVictor Hugo06-19-2012

    for me this works perfect! i use as a plugin for a very specific custom post type that i create before, i just have a question, can i get images upload to my editor, this new function change the original behavior of “insert into post”, now when i choose the original uploader and click on insert into post, nothing happens, any help?

  104. BarbaraBarbara07-16-2012

    Hi,

    Anyone know how I can attach the image to the correct post?

  105. RickyRicky08-06-2012

    Same question as above, anybody knows how to output images in different sizes? Like thumbnail, medium, large?
    great tuts tank u Micheal

Leave a Reply

Have a question? Give us a call! 305-741-4742