samedi 25 juin 2016

Wordpress image upload from frontend throws 500 internal server error

I have a site with a frontend form where users can add new post. The form has some basic post details and an featured image field. The form also has a few more image fields, which are controlled by acf.

Now the issue is when i use images like png everything works fine. But when i use images like jpg, it gives a internal server error. In acf i have added the accepted file formats as "jpg,png,jpeg". But i am not sure how to add file formats for the featured image.

Here is the code i am using. Here the first image will always be the featured image.

        foreach( $_FILES as $file ) {
            if( is_array( $file ) ) {
                if($count==1){
                    $featured_image_id = upload_user_file( $file );
                }else{
                    $item_image[] = upload_user_file( $file );

                }
            }
            $count++;
          }

And here is the upload_user_file function

function upload_user_file( $file = array() ) {
    require_once( ABSPATH . 'wp-admin/includes/admin.php' );
      $file_return = wp_handle_upload( $file, array('test_form' => false ) );
      if( isset( $file_return['error'] ) || isset( $file_return['upload_error_handler'] ) ) {
          return false;
      } else {
          $filename = $file_return['file'];
          $attachment = array(
              'post_mime_type' => $file_return['type'],
              'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
              'post_content' => '',
              'post_status' => 'inherit',
              'guid' => $file_return['url']
          );
          $attachment_id = wp_insert_attachment( $attachment, $file_return['url'] );
          require_once(ABSPATH . 'wp-admin/includes/image.php');
          $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
          wp_update_attachment_metadata( $attachment_id, $attachment_data );
          if( 0 < intval( $attachment_id ) ) {
            return $attachment_id;
          }
      }
      return false;
}



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire