Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I'm working on adding the possibility to add some custom_post_type from the front end. I can link Images to them, but apparently they are not resized. And I really need the special sizes that I have define on my functions.php.

Here is what I do :

if(!empty($_FILES['IMAGE'])){
        include_once ABSPATH . 'wp-admin/includes/media.php';
        include_once ABSPATH . 'wp-admin/includes/file.php';
        include_once ABSPATH . 'wp-admin/includes/image.php';
        $file = $_FILES['IMAGE'];

        $upload = wp_handle_upload( $file, array('test_form' => false));
          if(!isset($upload['error']) && isset($upload['file'])){
            $title = $file['name'];

            $filetype = wp_check_filetype( basename($upload['file'], null ));

            $ext = strrchr($title,'.');
            $title =($ext !== false) ? substr($title, 0, -strlen($ext)) : $title;

              //$url_img = wp_get_attachment_url( $attach_key );
              $attach_key = '_thumbnail_id';
              $attach_id = wp_insert_attachment($attachment,$upload['file']);
              $existing_download = (int) get_post_meta($new_eta_ID, $attach_key, true);
              if(is_numeric($existing_download)){
                wp_delete_attachment( $existing_download );
              }
              update_post_meta($new_eta_ID, $attach_key, $attach_id,true);
          }
      }

So it uploads the selected files, but it's not resizing. How can I do that ?

Thanks !

share|improve this question

1 Answer 1

up vote 0 down vote accepted

The following code is taken from my "Dynamic image resize"-plugin.

The plugin takes an ID as well as a string into account. I didn't delete those lines, as they might be usable for later visitors - check the link anyway.

Retrieve the image by ID or URl

    $hw_string    = image_hwstring( $width, $height );

    $needs_resize = true;

    $error        = false;
    // ID as src
    if ( ! is_string( $src ) )
    {
        $att_id = $src;
        // returns false on failure
        $src    = wp_get_attachment_url( $src );

        // If nothing was found:
        ! $src AND $error = true;
    }
    // Path as src
    else
    {
        $upload_dir = wp_upload_dir();
        $base_url   = $upload_dir['baseurl'];

        // Let's see if the image belongs to our uploads directory...
        $img_url = substr(
             $src
            ,0
            ,strlen( $base_url )
        );
        // ...And if not: just return the image HTML string
        if ( $img_url !== $base_url )
        {
            return $this->get_markup(
                 $img_url
                ,$hw_string
                ,$classes
            );
        }

        // Look up the file in the database.
        $file   = str_replace(
             trailingslashit( $base_url )
            ,''
            ,$src
        );
        $att_id = $this->get_attachment( $file );

        // If no attachment record was found:
        ! $att_id AND $error = true;
    }

Check for Errors

and abort if no Attachment was found. This would mean the upload didn't end as expected.

    // Abort if the attachment wasn't found
    if ( $error )
    {
        # @TODO Error handling with proper message
        # @TODO Needs a test case
        # remove $file in favor of $error_msg
        /*
        $data = get_plugin_data( __FILE__ );
        $error_msg = "Plugin: {$data['Name']}: Version {$data['Version']}";
        */

        # @TODO In case, we got an ID, but found no image: if ( ! $src ) $file = $att_id;

        return new WP_Error(
             'no_attachment'
            ,__( 'Attachment not found.', 'dyn_textdomain' )
            ,$file
        );
    }

Check already existing image sizes

In case there already was an image of the size we need. This might be the case if the user tries to upload the same image multiple times (which you'd have to check to avoid duplicates).

    // Look through the attachment meta data for an image that fits our size.
    $meta = wp_get_attachment_metadata( $att_id );
    foreach( $meta['sizes'] as $key => $size )
    {
        if (
            $width === $size['width']
            AND $height === $size['height']
            )
        {
            $src = str_replace(
                 basename( $src )
                ,$size['file']
                ,$src
            );
            $needs_resize = false;
            break;
        }
    }

Process the resize

Now we're sure we got an attachment and need to resize. We as well update the post and attachment post type meta data.

    // If an image of such size was not found, ...
    if ( $needs_resize )
    {
        $attached_file = get_attached_file( $att_id );
        // ...we can create one.
        $resized       = image_make_intermediate_size(
             $attached_file
            ,$width
            ,$height
            ,true
        );

        if ( ! is_wp_error( $resized ) )
        {
            // Let metadata know about our new size.
            $key = sprintf(
                 'resized-%dx%d'
                ,$width
                ,$height
            );
            $meta['sizes'][ $key ] = $resized;
            $src = str_replace(
                 basename( $src )
                ,$resized['file']
                ,$src
            );

            wp_update_attachment_metadata( $att_id, $meta );

            // Record in backup sizes, so everything's
            // cleaned up when attachment is deleted.
            $backup_sizes = get_post_meta(
                 $att_id
                ,'_wp_attachment_backup_sizes'
                ,true
            );

            ! is_array( $backup_sizes ) AND $backup_sizes = array();

            $backup_sizes[ $key ] = $resized;

            update_post_meta(
                 $att_id
                ,'_wp_attachment_backup_sizes'
                ,$backup_sizes
            );
        }

Now everything should be fine and ready to go on.

If you don't need everything, just drop what you don't need, but make sure you don't leave out the needed error checks. Better safe than sorry.

share|improve this answer
1  
Thank you, that was really helpful ! –  user1470645 Jun 28 '13 at 11:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.