Dzień dobry!
This can be a very dangerous modification if not carefully implemented. A large portion of site hacks are executed through badly conceived image upload functionality.
I can’t tell you exactly what to do, but I can give you some hints that should lead to success. You basically just want to implement an image upload via AJAX functionality. There’s plenty of generic tutorials on how to do this. You’ll have to do some interpreting of the tutorials to make the code work in the WP environment.
For example, you cannot just place <script>
blocks anywhere convenient, such code should be enqueued with wp_enqueue_script()
. Similar for any CSS you may need. The WP implementation of AJAX is different than the generic examples you will see. The primary difference is how all requests have to be routed through admin-ajax.php
and how admin-ajax ends up executing your AJAX handler code.
Another challenge is getting the proper input and form HTML onto the profile page in a clean manner where core code is not altered. Compound that with the fact you cannot nest <form>
blocks, and your options are limited. There is no hook to use after the main form. There are a couple before, but they are VERY early. Refer to wp-admin/user-edit.php
. Perhaps CSS can be used to move the file field around?
Another possibility is using the ‘user_edit_form_tag’ action to make the main form the correct type by echoing out enctype="multipart/form-data"
Then you can use one of the actions inside the form to output the file field. The entire form would end up being submitted, but I believe ignoring everything but the file data will work since users would not expect an upload button to update all the other fields. I’m unsure if altering the enctype will impact how the rest of the form is saved. Be sure to test this before spending much time on this approach.
If all else fails, you should be able to introduce custom content using jQuery.
Once you get the file onto the server, it’s critical to do everything possible to ensure the upload is indeed an image, that it’s not too large, etc. This is a major security essay in itself.
You’d store the image anywhere that’s meaningful, storing the location in user meta is a great idea. When the profile page loads, you display the image if it exists, along with a “change” link or something that displays (via javascript) the file fields onclick. Or simply show the fields all the time, image or not.
You’re probably feeling overwhelmed at this point. As usual, break things down into small achievable tasks. Just focus on the task at hand. Eventually you’ll get it all working. I’d start by getting the file fields on the profile page, followed by sending an AJAX request to the server. If there’s something about how the page is configured that prevents this, there is no point in spending time on anything else.