I have a form that allows users to change their account settings, including their profile picture. Everything works fine, but if the user tries to save the settings without loading any images then the array to string conversion in error occurs.
If I do var_dump($attachment_id); I get object (WP_Error) #25169 (3) {["errors"] => array(1) {["upload_error"] => array(1) {[0] => string(21) "No file was uploaded. " }} ["error_data"] => array(0) {} ["additional_data": protected] => array (0) {}}
What am I doing wrong ?
Array to string conversion in: update_user_meta($user_id, 'image', $_FILES ['image']. ":". $attachment_id->get_error_message ());
This is where the error occurs
if ( is_wp_error( $attachment_id ) ) {
// The error occurs on the next line (update_uder_meta)
update_user_meta( $user_id, 'image', $_FILES['image'] . ": " . $attachment_id->get_error_message() );
}
This is the complete code
// Save Avatar Action
function action_woocommerce_save_account_details( $user_id ) {
if ( isset( $_FILES['image'] ) ) {
require_once( ABSPATH . 'wp-admin/includes/image.php' );
require_once( ABSPATH . 'wp-admin/includes/file.php' );
require_once( ABSPATH . 'wp-admin/includes/media.php' );
function wp_set_custom_upload_folder($uploads) {
$uploads['path'] = $uploads['basedir'] . '/avatar-upload';
$uploads['url'] = $uploads['baseurl'] . '/avatar-upload';
if (!file_exists($uploads['path'])) {
mkdir($uploads['path'], 0755, true);
}
return $uploads;
}
add_filter('upload_dir', 'wp_set_custom_upload_folder');
$attachment_id = media_handle_upload( 'image', 0 );
if ( is_wp_error( $attachment_id ) ) {
// The error occurs on the next line (update_uder_meta)
update_user_meta( $user_id, 'image', $_FILES['image'] . ": " . $attachment_id->get_error_message() );
} else {
$old_attachment_id = get_user_meta( $user_id, 'image', true );
wp_delete_attachment($old_attachment_id);
update_user_meta( $user_id, 'image', $attachment_id );
}
remove_filter('upload_dir', 'wp_set_custom_upload_folder');
}
}
add_action( 'woocommerce_save_account_details', 'action_woocommerce_save_account_details', 10, 1 );