I have a custom account page in WordPress where I would like users to be able to upload an image that replaces the default WordPress avatar. I have the upload process working great, but I need to crop the images to make sure they are all squares and not too large. Below is the code that I have. I think the issue is with the $image = wp_get_image_editor($path_file); line because the if clause below it is not running.

function mepr_save_account_fields($user) {
  $the_user     = MeprUtils::get_currentuserinfo();
  $upload_info  = wp_upload_dir();
  $upload_url   = $upload_info['baseurl'] . '/user_avatars/';
  $upload_dir   = $upload_info['basedir'] . '/user_avatars/';

  $target_file  = $upload_dir . basename($_FILES["mepr_avatar"]["name"]);
  $target_url   = $upload_url . basename($_FILES["mepr_avatar"]["name"]);

  // Crop Image
  $parsed_file  = parse_url($target_file);
  $parsed_url   = parse_url($target_url);

  $path_file = $_SERVER['DOCUMENT_ROOT'] . $parsed_file['path'];
  $path_url  = 'https://' . $_SERVER['HTTP_HOST'] . $parsed_url['path'];

  $image = wp_get_image_editor($path_file);
  if ( ! is_wp_error( $image ) ) {
     //true indicates to crop image.
     $result = $image->resize( 200,200,true );
     $result = $image->save($path_file);
  move_uploaded_file($_FILES["mepr_avatar"]["tmp_name"], $target_file);

  //update info
  update_user_meta($the_user->ID, 'mepr_custom_avatar', $target_url);
  • It's probably an error, have you looked at the output of the error, the message might tell you what's wrong. $image->get_error_message(); – totels Jun 2 '17 at 20:07
  • @totels Good idea. The error doesn't help much though. It simply says 'Failed to read the file' when I try with $image = wp_get_image_editor($path_url); and 'No file found' when I try with $image = wp_get_image_editor($path_file);. Are my path variables incorrect? – Andrew Jun 2 '17 at 21:12
  • $path_url definitely won't work. You probably need to debug $path_file to see if it's pointing to the location you expect. – totels Jun 2 '17 at 22:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.