0

I have a front end user profile template I am working on, and everything is working fine except for upload a profile picture. I have a custom user field created and I am trying to use the button file type to upload the picture and store the URL in my custom field.

Take a look - https://pastebin.com/rPErwCgU

I'm currently already using this code for my front end post upload, it allows multiple pictures. I need to figure out how to do this for a user with only 1 photo and storing it in a custom field attached to the current user --

if (!empty($_FILES['sightMulti']['tmp_name'][0])) {
    $i = 1;
    $files = $_FILES['sightMulti'];
    foreach ($files['name'] as $key => $value) {
        if ($files['name'][$key]) {
            $file = array(
                'name' => $files['name'][$key],
                'type' => $files['type'][$key],
                'tmp_name' => $files['tmp_name'][$key],
                'error' => $files['error'][$key],
                'size' => $files['size'][$key]
            );
            $_FILES = array("sight" . $i => $file);
            $newuploadMulti = sight("sight" . $i, $pid);
            if ($i == 1) {
                update_post_meta($pid, '_thumbnail_id', $newuploadMulti);
            }
            add_post_meta($pid, 'imic_property_sights', $newuploadMulti, false);
        }
        $i++;
    }
}

The field in the form --

<div class="col-md-12 col-sm-12">
        <label><?php _e('Upload Images', 'framework'); ?></label>
        <p><?php _e('Upload images that are best clicked for better appearance of your property', 'framework'); ?></p> 
</div>
<div class="row" id="multiplePhotos" style="margin-top:15px;">
    <div class="col-md-12 col-sm-12">
        <?php
        echo'<div class="image-placeholder" id="photoList">';
        if (!empty($property_sights_value)) {
            foreach ($property_sights_value as $property_sights) {
                $default_featured_image = get_post_meta($Property_Id, '_thumbnail_id', true);
                if ($default_featured_image == $property_sights) {
                    $def_class = 'default-feat-image';
                } else {
                    $def_class = '';
                }
                echo '<div class="col-md-2 col-sm-2">';
                echo '<div id="property-img"><div id="property-thumb" class="' . $def_class . '"><a id="feat-image" class="accent-color default-image" data-original-title="Set as default image" data-toggle="tooltip" style="text-decoration:none;" href="#"><div class="property-details" style="display:none;"><span class="property-id">' . $Property_Id . '</span><span class="thumb-id">' . $property_sights . '</span></div><img src="' . wp_get_attachment_thumb_url($property_sights) . '" class="image-placeholder" id="filePhoto2" alt=""/></a>';
                if (get_query_var('site')) {
                    echo '<input rel="' . $Property_Id . '" type="button" id="' . $property_sights . '" value="Remove" class="btn btn-sm btn-default remove-image">';
                }
                echo '</div></div>';
                echo '</div>';
            }
        }
        echo '</div>';
        ?>
        <input id="filePhotoMulti" type="file" name="sightMulti[]" multiple onChange="previewMultiPhotos();">
    </div>
</div>

UPDATE

This is what I have right up top with the rest of my fields that save fine -

if ( !empty( $_POST['agent-image'] ) )
update_user_meta( $current_user->ID, 'agent_image', esc_attr( $_POST['agent-image'] ) );

if(!empty($_FILES)) {
$uploaddir = wp_upload_dir();

$file = $_FILES[agent-image];

$uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );

move_uploaded_file( $file['tmp_name'] , $uploadfile );

$filename = basename( $uploadfile );

$wp_filetype = wp_check_filetype(basename($filename), null );

$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => preg_replace('/\.[^.]+$/', '', $filename),
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
}

My input field --

<input type="file" name="agent-image">

How I'm using it on the author.php template --

<?php 
$author_pic = get_the_author_meta('agent-image', $user->ID);
echo '<div><img src="'. $author_pic .'" alt="'. $userName .'" class="img-thumbnail authppic"></div>'; ?>

UPDATE 2

Code is now causing that page to give me a HTTP 500 error --

if ( !empty( $_FILES[agent-image][name] )) {
$uploaddir = wp_upload_dir();

$file = $_FILES[agent-image];

$uploadfile = $uploaddir['path'] . '/' . basename( $file['name'] );

move_uploaded_file( $file['tmp_name'] , $uploadfile );

$filename = basename( $uploadfile );

$wp_filetype = wp_check_filetype(basename($filename), null );

$attachment = array(
    'post_mime_type' => $wp_filetype['type'],
    'post_title'     => preg_replace('/\.[^.]+$/', '', $filename),
);

$attach_id = wp_insert_attachment( $attachment, $uploadfile );
update_user_meta( $current_user->ID, 'agent_image', $attach_id ));
}

bumped to the homepage by Community yesterday

This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.

  • 1
    Where or how do you process the file information after the input? – CK MacLeod Oct 8 '17 at 17:50
  • There is no code to handle the input 'agent-image'? – lukgoh Oct 8 '17 at 18:03
  • sorry bro, but the code you linked is a miss and contain many deprecated WordPress code, you can check this link to add front end user profile – IBRAHIM EZZAT Oct 9 '17 at 17:26
  • questions should be self contained, not ask people to go round the web to try to understand what is it you are asking.... assuming you are intrested in a useful answer :( – Mark Kaplun Oct 9 '17 at 17:30
  • 1
    if it is straight forward why do people need to go to another site to learn what it is? – Mark Kaplun Oct 9 '17 at 20:39
0

UPDATE: As mentioned in the comments, you might want to learn how you do things like create meta boxes and do a file upload in Wordpress without using a framework like CMB2 first. However, as a seasoned Wordpress developer, I have found that using CMB2 greatly increased my productivity.

I highly recommend using CMB2 to create a front end form for editing a user profile. I just did the same thing and I modified the code from these links:

You have 3 functions (function names are from the second linked article above): One registers the cmb2 fields

function wds_frontend_form_register() {
//code..
}

One create a shortcode for displaying the form:

function wds_do_frontend_form_submission_shortcode( $atts = array() ) {
//code..
}

and the third handles the submission of the form:

function wds_handle_frontend_new_post_form_submission( $cmb, $post_data = array() ) {
//code..
}

You can easily update your user instead of inserting a post here with wp_update_user() and update_user_meta().

Full code examples are available through the links. CMB2 field types reference docs here. Link to file field type (allowing image upload).

This linked example-functions.php also has an example for editing user profile fields (but this automatically hooks into the admin side). Handy if you also want to add fields there.

Good luck. I really recommend CMB2 it is brilliant.

  • 2
    use a plugin is rarely a good answer around here as it teaches nothing – Mark Kaplun Oct 10 '17 at 9:54
  • @MarkKaplun it is a library not a plugin and I think a lot of people would disagree with you in this case. Have you even looked at it? CMB2 is the main competitor of ACF which is one the defacto ways of doing advanced fields in Wordpress. It is well written, organised, supported, builds on existing WP api. Can't see why no one would be learning here. – Andrew Welch Oct 10 '17 at 10:13
  • and it is bloated way over the needs of answering this simple question. There should be a very good reason to add 10k lines of code to your theme where 50 would have been enough – Mark Kaplun Oct 10 '17 at 10:44
  • 1
    There might be a context where using CMB2 is a very good idea. I use it in pretty much every single large scale, professional WP project I do because it is so useful. Not every example on this forum has to be the most simple, smallest lines of code / use case. Code is all about building on the foundations of others. Still don't see why this isn't a valid contribution. – Andrew Welch Oct 10 '17 at 10:50
  • there is no reason to use either CMB2, ACF or whatever. writing metaboxes is easy and it just makes your life harder when the libraries limit you. – Mark Kaplun Oct 10 '17 at 11:06
0
if ( !empty( $_FILES[agent-image][name] ) ) {

                $file = $_FILES[agent-image];

                $file_return = wp_handle_upload( $file, array('action' => 'tm_about_you' ) );

                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'] );

                    // Generate the metadata for the attachment, and update the database record.
                    $attachment_data = wp_generate_attachment_metadata( $attachment_id, $filename );
                    wp_update_attachment_metadata( $attachment_id, $attachment_data );

                    update_user_meta( $current_user->ID, 'agent_image', $attachment_id ));

                }

            }
  • Im already doing something similar for my front end posts. I've updated my question. – Rich Oct 9 '17 at 21:30
  • how does this apply to my situation? – Rich Oct 12 '17 at 6:07
  • At the time I posted this I commented on your question saying you didn't have any code to handle the file upload on the front end, you responded with: "that's the problem" so I gave you the code? – lukgoh Oct 12 '17 at 8:16
  • Ok what I meant is how can this be used as an answer to my question. – Rich Oct 12 '17 at 23:13
  • Oh sorry, so change this: $_FILES[featured_image]; to what ever your input name is set to. Then replace: $attach_id = wp_insert_attachment( $attachment, $uploadfile ); set_post_thumbnail( $page, $attach_id ); With adding the file to your custom field. – lukgoh Oct 13 '17 at 9:10

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.