I have a function for woocommerce (Add a profile picture (file upload) on My account > edit account in WooCommerce) that allows users to upload their frontend avatars from the account> settings section. Everything works fine but the images are loaded into the default media library. Is it possible to somehow change the directory by creating a new one for the purpose?
I appreciate any help and thank you for any replies.
Here is my code:
// Add field
function action_woocommerce_edit_account_form_start() {
?>
<p class="woocommerce-form-row woocommerce-form-row--wide form-row form-row-wide">
<label for="image"><?php esc_html_e( 'Image', 'woocommerce' ); ?> <span class="required">*</span></label>
<input type="file" class="woocommerce-Input" name="image" accept="image/x-png,image/gif,image/jpeg">
</p>
<?php
}
add_action( 'woocommerce_edit_account_form_start', 'action_woocommerce_edit_account_form_start' );
// Validate
function action_woocommerce_save_account_details_errors( $args ){
if ( isset($_POST['image']) && empty($_POST['image']) ) {
$args->add( 'image_error', __( 'Please provide a valid image', 'woocommerce' ) );
}
}
add_action( 'woocommerce_save_account_details_errors','action_woocommerce_save_account_details_errors', 10, 1 );
// Save
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' );
$attachment_id = media_handle_upload( 'image', 0 );
if ( is_wp_error( $attachment_id ) ) {
update_user_meta( $user_id, 'image', $_FILES['image'] . ": " . $attachment_id->get_error_message() );
} else {
update_user_meta( $user_id, 'image', $attachment_id );
}
}
}
add_action( 'woocommerce_save_account_details', 'action_woocommerce_save_account_details', 10, 1 );
// Add enctype to form to allow image upload
function action_woocommerce_edit_account_form_tag() {
echo 'enctype="multipart/form-data"';
}
add_action( 'woocommerce_edit_account_form_tag', 'action_woocommerce_edit_account_form_tag' );
3
Answers
I solved it like this, I don't know if it's correct and practical but it's working.
the thing with WordPress is that avatars are quite weird. I would suggest adding a plugin for this that uploads avatars since the container for them is different then and it might show up. The problem you have is that the image goes to another container. Overall all images on a site will be uploaded to the gallery
If I understood your question correctly, you want to change the default location of an uploaded file. If this is the case, go to the
wp-config.php
file in the root directory and specify an address like this:For detailed information, you can visit the official
wp-config.php
page of WordPress: https://developer.wordpress.org/apis/wp-config-php/