Change an avatar created with advanced custom fields from the frontend

0

I use the latest pro version of ACF. With this I have assigned an image as an avatar that is then seen in the custom-profiole-template that I have made. My problem is that this avatar must be able to change from the same frontend by attaching a new image and deleted the old one, and I have no idea how to make it do so. I have looked at the documentation of ACF like 60 times and in the end I come to the same viaduct At the moment this is like this

<form>
     <div id="img-logo"><?php echo get_avatar( $current_user->ID ); ?></div>

           <div id="inputfile">
                <input type="file" name="file">
                <input type="submit" for="file">
           </div> 
 </form>

I know it's not much, but I do not know how to do it, I tried it with acf_form custom array, but it did not come to fruition either. Can someone help me?

    
asked by Dario B. 18.04.2018 в 08:33
source

1 answer

1

Well the first thing you have to do is to have your form upload the file to your wordpress. You can work with the function wp_handle_upload

link

This function will upload your image, create the post in the database and respond with the URL of the image and its ID. You need to send the file as a parameter.

function addImage($file){

    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 ) ) {

            $response = [
              'ID' => $attachment_id,
              'url' => $file_return['url']
            ];

            return $response;
          }
      }

      return false;
    }

When the file is up you can update the ACF with the URL of the avatar and in the user ID which you can obtain with the function get_current_user_id()

I hope it works for you.

    
answered by 03.08.2018 / 20:29
source