Support

Account

Home Forums General Issues Uploading Image/File on the front-end

Solved

Uploading Image/File on the front-end

  • I have built a custom page for my logged on users.

    The ‘update_field’ function works well for text based values. But the Image and File fields are giving me trouble.

    How could I reproduce the same UI from the backend on my custom page?

    I’m a bit lost here. Thank you.

  • Hi @EtienneDupuis

    The image field expects an attachment ID to be saved as the meta value.

    You need to use some WP functions to insert the image into the DB and file system, which will return an ID for you to use!

    Thanks
    E

  • This is what I did. Thanks.

    //Upload la photo dans le dossier
    require_once(ABSPATH.’wp-admin/includes/file.php’);
    $uploadedfile = $_FILES[‘photo’];
    $movefile = wp_handle_upload($uploadedfile, array(‘test_form’ => false));

    //On sauvegarde la photo dans le média library
    if ($movefile) {
    $wp_upload_dir = wp_upload_dir();
    $attachment = array(
    ‘guid’ => $wp_upload_dir[‘url’].’/’.basename($movefile[‘file’]),
    ‘post_mime_type’ => $movefile[‘type’],
    ‘post_title’ => preg_replace(‘/\.[^.]+$/’, ”, basename($movefile[‘file’])),
    ‘post_content’ => ”,
    ‘post_status’ => ‘inherit’
    );
    $attach_id = wp_insert_attachment($attachment, $movefile[‘file’]);

    update_field(‘photo’, $attach_id, ‘user_’.$current_user->ID);
    }

  • Thank you Etienne. You got me on the right track. Here is the full code that should go in functions.php:

    // Deal with images uploaded from the front-end while allowing ACF to do it’s thing
    function my_acf_pre_save_post($post_id) {

    if ( !function_exists(‘wp_handle_upload’) ) {
    require_once(ABSPATH . ‘wp-admin/includes/file.php’);
    }

    // Move file to media library
    $movefile = wp_handle_upload( $_FILES[‘my_image_upload’], array(‘test_form’ => false) );

    // If move was successful, insert WordPress attachment
    if ( $movefile && !isset($movefile[‘error’]) ) {
    $wp_upload_dir = wp_upload_dir();
    $attachment = array(
    ‘guid’ => $wp_upload_dir[‘url’] . ‘/’ . basename($movefile[‘file’]),
    ‘post_mime_type’ => $movefile[‘type’],
    ‘post_title’ => preg_replace( ‘/\.[^.]+$/’, ”, basename($movefile[‘file’]) ),
    ‘post_content’ => ”,
    ‘post_status’ => ‘inherit’
    );
    $attach_id = wp_insert_attachment($attachment, $movefile[‘file’]);

    // Assign the file as the featured image
    set_post_thumbnail($post_id, $attach_id);
    update_field(‘my_image_upload’, $attach_id, $post_id);

    }

    return $post_id;

    }

    add_filter(‘acf/pre_save_post’ , ‘my_acf_pre_save_post’);

  • Beware that this site converts straight quotes to curly quotes.

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Uploading Image/File on the front-end’ is closed to new replies.