Including Images as Attachments or Featured Image in Post From Front End Form

Yesterday we covered how to create a form on the front end which allows users to post. It’s time to expand on that idea in a couple of ways. Today we will cover how to allow images to be uploaded along with the post. And we will show show options, you can add the image(s) as attachments and display them with the post, you can assign an image as the_post_thumbnail featured image, or both (which is what I do). If you haven’t reviewed the above linked article, check it out. Now let’s add some image uploads!

I have to give credit where it is due. Most, if not all, of this code came from @Bainternet over on the WordPress StackExchange site. I did a lot of Googling, and a lot of testing before I got this fairly simple solution running perfectly. So with credit given, let’s look at the code that worked for me.

The first thing we need to allow the uploads, is a little function dropped into functions.php.

function insert_attachment($file_handler,$post_id,$setthumb='false') {
	// check to make sure its a successful upload
	if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

	require_once(ABSPATH . "wp-admin" . '/includes/image.php');
	require_once(ABSPATH . "wp-admin" . '/includes/file.php');
	require_once(ABSPATH . "wp-admin" . '/includes/media.php');

	$attach_id = media_handle_upload( $file_handler, $post_id );

}

That bit of code in your functions.php will set up the image uploads. It doesn’t do anything yet, we need to set things up in our form. We will get to that in a minute. The next thing to consider is, do you want the image to be set as the post thumbnail/featured image? I know I did, I like all my posts to have featured images attached. So we add a couple of lines to the above code in functions.php so that it sets the featured image. The code now looks like:

function insert_attachment($file_handler,$post_id,$setthumb='false') {
	// check to make sure its a successful upload
	if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();

	require_once(ABSPATH . "wp-admin" . '/includes/image.php');
	require_once(ABSPATH . "wp-admin" . '/includes/file.php');
	require_once(ABSPATH . "wp-admin" . '/includes/media.php');

	$attach_id = media_handle_upload( $file_handler, $post_id );

	if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
	return $attach_id;
}

So that will allow the uploads, and also set the image as your featured image. Just a note, if you allow multiple image uploads (as I do) then the last image uploaded will be the featured image. I’m sure there is a way to loop through and pick which image to use as the featured image, but I just kept it like this. I allow 2 images, so the last one uploaded (the bottom one in the form code) becomes the featured image.

The next thing we need to do is add in the image upload fields to the form we made yesterday. This is pretty simple. Just follow along with the same format we used for the other fields. Here’s what my two image fields look like:

			<!-- images -->
			<fieldset class="images">
			<label for="images">Front of the Bottle</label>
			<input type="file" name="bottle_front" id="bottle_front" size="50">
			</fieldset>

			<fieldset class="images">
			<label for="images">Back of the Bottle</label>
			<input type="file" name="bottle_rear" id="bottle_rear" size="50">
			</fieldset>

Just simple input fields which allow for the file input type. Now we need to edit the first line of code for the form. Currently we have:

<form id="new_post" name="new_post" method="post" action="" class="wpcf7-form">

And we simply need to update that to:

<!-- Add the enctype at the end -->
<form id="new_post" name="new_post" method="post" action="" class="wpcf7-form" enctype="multipart/form-data">

And that is it for the form. We have our image uploading fields, and we’ve told our form to accept the uploads. Now we need the processing code. Underneath the wp_insert_post line from yesterday, which looks like:

$pid = wp_insert_post($new_post);

We add in this code:

if ($_FILES) {
	foreach ($_FILES as $file => $array) {
	$newupload = insert_attachment($file,$pid);
	// $newupload returns the attachment id of the file that
	// was just uploaded. Do whatever you want with that now.
	}
}

And that does it! We’ve now set up to allow for the upload of two images (you can use more or less), and we’ve assigned an image as the featured image. One last bit of code. So far we’ve attached the image to the post, but we haven’t inserted them. So let’s look at how to call the images to be displayed with our posts. You will need to locate the template used to display these posts. This totally depends on your theme. In my case, because I set up my child theme this way, separating out all my formats, I need to edit format-standard.php. You may need to add this to loop.php or index.php or single.php, etc.

I have added this code:

<div class="wineBottles">
<?php
$args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );
$attachments = get_posts($args);
if ($attachments) {
	foreach ( $attachments as $attachment ) { ?>
		<div class="wineImage">
			<span class="wineTitle">
		<?php echo apply_filters( 'the_title' , $attachment->post_title ); ?>
			</span>
		<?php the_attachment_link( $attachment->ID , false ); ?>
		</div>
	<?php }
}
?>
</div>
		<div class="clear"></div>

I located that underneath my title code, and above the_content. Where you add it is entirely up to you and where you want the images. But this is a loop (for use inside a loop) which cycles through and displays all your images uploaded from the form. You’ll see my css selectors set up here. Div class wineBottles wraps all the images, wineImage wraps each individual image/title and the span wineTitle just wraps the title. You can get rid of lines 8-10 if you don’t want the image title to be used. Which I’m thinking of doing.

And that does it! You now have image uploads available from the front end. Tomorrow we will cover adding meta boxes to your form to make use of custom fields for gathering additional data. And after that, we will do a quick wrap-up. Just to show all the code I have in whole. Stay tuned!

80 thoughts on “Including Images as Attachments or Featured Image in Post From Front End Form

  1. I’ve been waiting for a plugin to use with WordPress that allows front end posting with images. Preferably setting an image uploaded as the featured image. I’ve found three plugins that exist and all are fairly new and lacking this feature, and it seems all of the plugin authors have given up on trying to do this. The best plugin so far is called “WordPress User Frontend” because it allows the frontend user the ability to create and edit their own posts. However, it does not have the ability to upload images in it’s form.

    What I’m basically getting at: is there a way to edit a plugin to allow it to upload images and set the uploaded image to the featured image?

    • Honestly I have no idea. I tend to avoid plugins when I can code something into WP myself. If you look at the 2 recent tutorials I have up here, it is not a lot of code really to get a form going, and allow for image uploads.

      But plugin code, and theme code are really the same. If you can figure out how to implement the code I’ve given here into a plugin for image uploads, it will work from a plugin as well as from a theme.

      If I have time I may look into that plugin and see if I could figure out how to mesh the code. But time is pretty tight for me lately. Working full time + working on my masters = crazy busy….

      But the code I give is pretty flexible, it can be changed up to make things work however you want. Maybe you can get a post form without a plugin that does what you want.

      The only thing I’m not sure about is editing from the frontend, I’ve never looked into that at all. I may take a peek and see if I can make that work in the near future….

    • I second this! I have been trying for hours, placing your upload code into the post form and it does not work, it uploads the image but does not attach them to the post :(

      • You either have a conflict or a code error then. I have the code running on 2 sites, and it works perfectly. I can upload 2 images, both get attached, and the first one gets assigned as the featured image. I’ve gotten a tonne of feedback that this works perfectly for many users. So something is unique on your end. Do you also include the required code in functions.php?

    • I just tested on my install (I use this code at smashthegrape.com) where I’m developing my code.

      Everything works perfectly for me. I have it set up to allow 2 image uploads. Both images get attached to the post. One of them gets assigned as a featured image. And I’m able to display both posts. I’m about to make a new post reviewing everything from the past three tutorials and I’m going to show all my code all together, so maybe that will help you troubleshoot.

    • Dunno why I didn’t think to test that portion. I tested the form about 50 times to make sure it worked properly. I forgot to ever test to make sure it failed properly too.

    • Not yet. I’m trying to track things down from a few angles. Hoping someone can help with something simple. If not I’ll resort to coding something up. The thing is, every tutorial online shows to do the validation as it is here. So I can’t figure out why, if so many people show that, it doesn’t work. I’m hoping for a simple answer before I go reinventing the wheel. But if I don’t find out soon, I’ll figure it out on my own!

  2. How could I restrict the upload form to registered user and how could have a thumbnail for the index (list of posts) and a bigger image for the single post display with the implementation of wordpress 3 thumbnail support?
    Thanks for any guidance here.

  3. Thanks for this rev!
    i used the image upoading function in a plugin for uploading from frontend and its working a treat,
    regards

    • Good to hear! That’s very cool you used it in a plugin! That’s a neat idea, I’ve just learned how to start working with plugins and widgets. So that may be a neat idea for me to consider!

  4. i need your help..
    do you have any idea how to do this :
    Choose image to upload..
    After Selecting image..
    Without any clicking on Submit button..
    The page should show/display the user selected image.
    Not the image name.. the image itself in thumbnail size :)
    Please HELP me :)

    • I’m not 100% sure how to do this to be honest. I haven’t yet figured out a way to get a good image preview, which would be necessary to implement this. I’ll try to work on this some more soon.

  5. when can i actually email you my questions?
    I got a lot of question with php..
    The problem i posted above is solved already,
    now i’m stuck with “wp_dropdown_categories”.
    I got my parent categories listed..
    what i need now is..
    a select field for sub-categories.
    Please i need help.
    Your tutorials are the only one i “really” understand.
    Please.

    • Well, VoodooPress has a contact form where you can send requests. The problem is that I’m very busy at work right now, and I’m in school. So I have very little time. I will try to look into your issue today, if I have a few free minutes between work.

  6. Hi,

    Is there anyway to set the image to a default one if the user chooses not upload one in the form, sorry for asking so many questions. I’m new to this.

  7. Hello,
    Cant express how happy I am that i found this bit of code!!

    Just one query. I am using fancybox to display images. I have pasted your last bit of code to my index.php and it works great. However I was wondering if it is possible to display just one image from each post then when clicked the rest of the post attachments open in fancybox. so kind of hiding the rest of the post images until i call them??

    sorry been at it for days, thanks in advance for any help

    • I’d have to look into how fancybox works…. I’m sure it wouldn’t be hard to just display the single post. It’s a matter of figuring out how to only bring up the rest of the inmages when that one image is clicked….. Seems like it would be relatively simple, but I have to look at fancybox to see…

      • Hey,

        Thanks for the reply, been trying for a few days to figure this one out.

        Think it would be possible though the fancybox manual call (as seen at the bottom of their site http://fancybox.net/) just not too sure how to integrate this with wordpress to load the rest of the post images dynamically.

        Thanks for any help in advance :)

        • I mean… you’d have to decide how to grab the image you want displayed first. Either through a featured image or something like this:

          function firstimg($parent){
               global $wpdb;
               $image = wpdb->get_results('SELECT * FROM '.$wpdb->posts.' WHERE post_parent='.$parent.' AND post_type="attachment" AND post_mime_type LIKE "%image%" ORDER BY menu_order ASC LIMIT 1');
          
                return $image;
          }
          

          Which displays the first attached image. Then maybe wrap it in a link to display the gallery in fancybox, possibly using the above loop for grabbing all attached images.
          I’m getting error messages on the fancybox site when I try to look at the links for instructions. Not sure if its a problem on their end, or the fact that I’m stuck using IE7 at work…..

          • ps without the plugin I have managed to call each posts featured image to the home page but how would I ‘wrap it in a link to display the gallery in fancybox’ ??

          • Unfortunately, I can’t give any better ideas until the errors on the fancybox page let me see how to grab a gallery in the fancybox. The concept for wrapping the thumbnail is simply:

            <a href="link" rel="something">
            <?php the_post_thumbnail(); ?>
            </a>
            

            That wraps the thumbnail in a link. I was hoping the link could be used to call the gallery, but I can’t see the instructions for the gallery to know if this idea is possible.

      • thankss. i cant seem to find the link to instructions on the fancybox site. just examples of what it can do.

        I found the js which calls in images on the manual call just need to convert this into wordpress language + make it dynamic

        $(“#manual2″).click(function() {
        $.fancybox([
        'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
        'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
        {
        'href' : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
        'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
        }
        ], {
        ‘padding’ : 0,
        ‘transitionIn’ : ‘none’,
        ‘transitionOut’ : ‘none’,
        ‘type’ : ‘image’,
        ‘changeFade’ : 0
        });
        });

    • I have no way of knowing why it would work on one site and not another. It’s always worked for me. What’s different between the sites? Could be plugins, could be a theme conflict, some minor code issue, etc.

  8. So I implemented the form and image uploader and it worked splendidly. Then I had to use it on a site using Thesis as it’s theme… I can get the posts to work but not the image upload. I don’t know how to use the insert_attachement function in the Thesis custom_functions.php.

    I guess what I’m asking is if this can work on the thesis theme or not. Thanks!

  9. I am using some of the code above to upload on the front end. I was wondering if anyone knows how to also give the uploaded file a “Title”. Every attachment in the backend as fields like “Title”, “Alternate Text”, “Caption” and “Description” and I would like to also allow someone to give an attachment the Title and Description.

    Any direction (or even modified code from above) would be appreciated. Thanks

  10. Thanks for the tutorial, but its almost irresponsible in the hands of the unexperienced. There is no validation here, Its not a tutorial on how to include an image, but a tutorial on how to include any file. You should include a way to validate that it is actually an image. But again, thanks a bunch for the tutorial.

    • Yeah, I just kinda learn things as I need them, and then post what I learned here. This is just kind of a half baked idea for a specific purpose for me. The whole ‘posting from the front end’ series I did here got way more popular than I ever thought it would! But, I’m probably not going to go any further with it per se. WP 3.3 will be out soon, which is going to allow full access to the WP editor and file uploader. I think that is going to be way more powerful than what I’ve got started here. So as soon as I have a bit of time, I’m hoping to redo this series, with those new features.

  11. Pingback: Anonymous

  12. Hey, thanks for a great tutorial. I’m just having one problem. I’m not sure if it’s because I reduced the two image uploads to one, but for some reason if the user doesn’t upload an image I get a serialized error string in my postmeta table that says ‘No file was uploaded’. Because this is stored with the _thumbnail_id key, it’s breaking the default wp function has_post_thumbnail(). Is it possible that the if($FILES) check isn’t catching when there’s no image? Any ideas you have would be appreciated. Thanks!

    • Hm, not sure what could be going on there…. I don’t have this code set up anywhere at the moment. Not sure if the changes in WP 3.3 (with the editor, etc) could be affecting things. HOpefully I can get this back onto my test site shortly and give it a whirl

  13. Hi! Great tutorial! This really helped me a lot. I have one small question though; how can I change it so that the user can only upload one image by URL instead of a file selector? Any help would be very much appreciated!

  14. Hi,

    Thanks for a great tutorial. Very well explained indeed. It all seems to work except not only the uploaded image is shown in the post but it instead displays the entire wordpress media library one after the other!

    Anyone ideas on what might be causing this to happen?

    Thanks again.

    • Wow, no kidding? Hmm… I don’t have this installed anywhere anymore to troubleshoot… but let’s see if we can narrow it down first. When you go into edit post on the backend are just the expected images attached to the post? Or did all of them somehow get attached? If it’s just the expected items, then we can narrow down the problem to the foreach loop for display.

      • Great,

        No, when I go to the backend all of the images are not attached to the post(s), they can only be found in the media library and are images that belong to ‘auction posts’: I’m using this slightly annoying ‘AuctionTheme’ to set up an auction site which may be the cause of it.

        Seeing as I only need one image per post this works fine:

        if ( has_post_thumbnail() ) { // check if the post has a Post Thumbnail assigned to it.
        					  the_post_thumbnail('thumbnail');
        					} 

        But it’d still be good to figure out what is going wrong as i might like to add functionality for users to upload more than one image later.

        • I’d probably need to understand how the theme template where you are inserting the code works. The code I provided should definitely only get the images attached to the post, as we only loop through post type -> attachment, setting the post parent as the post ID. Which should only return to use images attached to each specific post. Are you doing this inside your loop? What template, like single.php, index.php, etc?

          • Thanks for your help. The theme is based on the sitemile framework which I am having trouble understanding and is not well documented.

            The code is actually going in functions.php in a function I made which is called from archive-area.php using:

            add_action('sitemile_do_post', "blueleaf_get_blog_post");

            I’m pretty sure it’s within the loop, but this is no ordinary wordpress template.

            Now if i print_r the attachments array before foreach ( $attachments as $attachment )
            it is HUGE!

          • I think it’s $post->ID that is not returning anything. If i use the specific ID of a post it’s working fine. Any suggestions on how to get the post id?

          • Well for anyone having this problem just add:

            $post = $wp_query->post;
            global $post;
            

            before the $args variable.

            Thanks for the awesome post Voodoo :)

          • I was just logging on here to help you out, but you found the problem!! When you are effecting the loop/query from functions.php, you need to globalize, and you did, good job! And thanks for reporting back here for future readers!

Leave a Reply

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

Connect with Facebook

*

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <img src="" alt="" width="" class="" style=""> <span style="">

To post code in your comments, simply wrap it in language tags.
[php][/php] [css][/css]