64 lines
2.4 KiB
PHP
64 lines
2.4 KiB
PHP
|
|
<?php
|
||
|
|
|
||
|
|
// 1. Добавляем enctype="multipart/form-data" к форме профиля
|
||
|
|
add_action('user_edit_form_tag', 'add_multipart_form_encoding');
|
||
|
|
function add_multipart_form_encoding() {
|
||
|
|
echo ' enctype="multipart/form-data"';
|
||
|
|
}
|
||
|
|
|
||
|
|
// 2. Добавляем поле для загрузки аватара
|
||
|
|
add_action('show_user_profile', 'extra_user_profile_fields');
|
||
|
|
add_action('edit_user_profile', 'extra_user_profile_fields');
|
||
|
|
function extra_user_profile_fields($user) {
|
||
|
|
?>
|
||
|
|
<h3><?php _e("Custom Avatar", "your-textdomain"); ?></h3>
|
||
|
|
<table class="form-table">
|
||
|
|
<tr>
|
||
|
|
<th><label for="avatar"><?php _e("Avatar"); ?></label></th>
|
||
|
|
<td>
|
||
|
|
<input type="file" name="avatar" id="avatar" />
|
||
|
|
<?php
|
||
|
|
$avatar = get_user_meta($user->ID, 'avatar', true);
|
||
|
|
if ($avatar) {
|
||
|
|
echo '<img src="' . esc_url($avatar) . '" width="100" style="display:block;margin-top:10px;" />';
|
||
|
|
echo '<p><input type="checkbox" name="remove_avatar" id="remove_avatar" /> <label for="remove_avatar">' . __('Remove avatar', 'your-textdomain') . '</label></p>';
|
||
|
|
}
|
||
|
|
?>
|
||
|
|
</td>
|
||
|
|
</tr>
|
||
|
|
</table>
|
||
|
|
<?php
|
||
|
|
}
|
||
|
|
|
||
|
|
// 3. Сохраняем аватар
|
||
|
|
add_action('personal_options_update', 'save_extra_user_profile_fields');
|
||
|
|
add_action('edit_user_profile_update', 'save_extra_user_profile_fields');
|
||
|
|
function save_extra_user_profile_fields($user_id) {
|
||
|
|
if (!current_user_can('edit_user', $user_id)) {
|
||
|
|
return false;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Удаление аватара
|
||
|
|
if (!empty($_POST['remove_avatar'])) {
|
||
|
|
delete_user_meta($user_id, 'avatar');
|
||
|
|
return;
|
||
|
|
}
|
||
|
|
|
||
|
|
// Загрузка нового аватара
|
||
|
|
if (!empty($_FILES['avatar']['name'])) {
|
||
|
|
if (!function_exists('wp_handle_upload')) {
|
||
|
|
require_once(ABSPATH . 'wp-admin/includes/file.php');
|
||
|
|
}
|
||
|
|
|
||
|
|
$uploadedfile = $_FILES['avatar'];
|
||
|
|
$upload_overrides = array('test_form' => false);
|
||
|
|
$movefile = wp_handle_upload($uploadedfile, $upload_overrides);
|
||
|
|
|
||
|
|
if ($movefile && !isset($movefile['error'])) {
|
||
|
|
update_user_meta($user_id, 'avatar', $movefile['url']);
|
||
|
|
} else {
|
||
|
|
// Обработка ошибки (можно вывести сообщение)
|
||
|
|
wp_die('Upload error: ' . $movefile['error']);
|
||
|
|
}
|
||
|
|
}
|
||
|
|
}
|