Загрузка аватара на фронтенде с помощью Simple Local Avatar
Я использую плагин Simple Local Avatars для загрузки пользовательских аватаров.
Как можно создать фронтенд-страницу с функцией загрузки аватара?
Ниже приведен код из плагина Simple Local Avatars:
<?php
/**
* Добавляем поле в профили пользователей
*/
class simple_local_avatars {
function simple_local_avatars() {
add_filter('get_avatar', array($this, 'get_avatar'), 10, 5);
add_action('admin_init', array($this, 'admin_init'));
add_action('show_user_profile', array($this, 'edit_user_profile'));
add_action('edit_user_profile', array($this, 'edit_user_profile'));
add_action('personal_options_update', array($this, 'edit_user_profile_update'));
add_action('edit_user_profile_update', array($this, 'edit_user_profile_update'));
add_filter('avatar_defaults', array($this, 'avatar_defaults'));
}
function get_avatar($avatar = '', $id_or_email, $size = '80', $default = '', $alt = false) {
if (is_numeric($id_or_email))
$user_id = (int) $id_or_email;
elseif (is_string($id_or_email)) {
if ($user = get_user_by_email($id_or_email))
$user_id = $user->ID;
} elseif (is_object($id_or_email) && !empty($id_or_email->user_id))
$user_id = (int) $id_or_email->user_id;
if (!empty($user_id))
$local_avatars = get_user_meta($user_id, 'simple_local_avatar', true);
if (!isset($local_avatars) || empty($local_avatars) || !isset($local_avatars['full'])) {
if (!empty($avatar))
return "<img src='http://www.wrongmag.ru/wp-content/themes/wrongmag/scripts/timthumb.php?src=/uploads/default-avatar.png&w={$size}&h={$size}&zc=1' class='avatar avatar-{$size} photo' height='{$size}' width='{$size}' />";
remove_filter('get_avatar', 'get_simple_local_avatar');
$avatar = get_avatar($id_or_email, $size, $default);
add_filter('get_avatar', 'get_simple_local_avatar', 10, 5);
return $avatar;
}
if (!is_numeric($size))
$size = '80';
if (empty($alt))
$alt = get_the_author_meta('display_name', $user_id);
if (empty($local_avatars[$size])) {
$upload_path = wp_upload_dir();
$avatar_full_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $local_avatars['full']);
$image_sized = image_resize($avatar_full_path, $size, $size, true);
if (is_wp_error($image_sized))
$local_avatars[$size] = $local_avatars['full'];
else
$local_avatars[$size] = str_replace($upload_path['basedir'], $upload_path['baseurl'], $image_sized);
update_user_meta($user_id, 'simple_local_avatar', $local_avatars);
} elseif (substr($local_avatars[$size], 0, 4) != 'http')
$local_avatars[$size] = site_url($local_avatars[$size]);
$author_class = is_author($user_id) ? ' current-author' : '';
$avatar = "<img alt='" . esc_attr($alt) . "' src='" . $local_avatars[$size] . "' class='avatar avatar-{$size}{$author_class} photo' height='{$size}' width='{$size}' />";
return $avatar;
}
function admin_init() {
load_plugin_textdomain('simple-local-avatars', false, dirname(plugin_basename(__FILE__)) . '/languages/');
register_setting('discussion', 'simple_local_avatars_caps', array($this, 'sanitize_options'));
add_settings_field('simple-local-avatars-caps', __('Права для локальных аватаров', 'simple-local-avatars'), array($this, 'avatar_settings_field'), 'discussion', 'avatars');
}
function sanitize_options($input) {
$new_input['simple_local_avatars_caps'] = empty($input['simple_local_avatars_caps']) ? 0 : 1;
return $new_input;
}
function avatar_settings_field($args) {
$options = get_option('simple_local_avatars_caps');
echo '<label for="simple_local_avatars_caps">
<input type="checkbox" name="simple_local_avatars_caps" id="simple_local_avatars_caps" value="1" ' . @checked($options['simple_local_avatars_caps'], 1, false) . ' />
' . __('Разрешить загрузку локальных аватаров только пользователям с правами загрузки файлов (Авторы и выше)', 'simple-local-avatars') . '
</label>';
}
function edit_user_profile($profileuser) {
?>
<h3><?php _e('Аватар', 'simple-local-avatars'); ?></h3>
<table class="form-table">
<tr>
<th><label for="simple-local-avatar"><?php _e('Загрузить аватар', 'simple-local-avatars'); ?></label></th>
<td style="width: 50px;" valign="top">
<?php echo get_avatar($profileuser->ID); ?>
</td>
<td>
<?php
$options = get_option('simple_local_avatars_caps');
if (empty($options['simple_local_avatars_caps']) || current_user_can('upload_files')) {
do_action('simple_local_avatar_notices');
wp_nonce_field('simple_local_avatar_nonce', '_simple_local_avatar_nonce', false);
?>
<input type="file" name="simple-local-avatar" id="simple-local-avatar" /><br />
<?php
if (empty($profileuser->simple_local_avatar))
echo '<span class="description">' . __('Локальный аватар не установлен. Используйте поле загрузки, чтобы добавить аватар.', 'simple-local-avatars') . '</span>';
else
echo '<input type="checkbox" name="simple-local-avatar-erase" value="1" /> ' . __('Удалить локальный аватар', 'simple-local-avatars') . '<br />
<span class="description">' . __('Замените локальный аватар, загрузив новый, или удалите его (откатившись к граватару), отметив опцию удаления.', 'simple-local-avatars') . '</span>';
} else {
if (empty($profileuser->simple_local_avatar))
echo '<span class="description">' . __('Локальный аватар не установлен. Настройте ваш аватар на Gravatar.com.', 'simple-local-avatars') . '</span>';
else
echo '<span class="description">' . __('У вас нет прав для управления медиафайлами. Для изменения локального аватара обратитесь к администратору сайта.', 'simple-local-avatars') . '</span>';
}
?>
</td>
</tr>
</table>
<script type="text/javascript">var form=document.getElementById('your-profile');form.encoding='multipart/form-data';form.setAttribute('enctype','multipart/form-data');</script>
<?php
}
function edit_user_profile_update($user_id) {
if (!wp_verify_nonce($_POST['_simple_local_avatar_nonce'], 'simple_local_avatar_nonce'))
return;
if (!empty($_FILES['simple-local-avatar']['name'])) {
$mimes = array(
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
'bmp' => 'image/bmp',
'tif|tiff' => 'image/tiff'
);
$avatar = wp_handle_upload($_FILES['simple-local-avatar'], array('mimes' => $mimes, 'test_form' => false));
if (empty($avatar['file'])) {
switch ($avatar['error']) {
case 'File type does not meet security guidelines. Try another.':
add_action('user_profile_update_errors', create_function('$a', '$a->add("avatar_error",__("Пожалуйста, загрузите корректный файл изображения для аватара.","simple-local-avatars"));'));
break;
default:
add_action('user_profile_update_errors', create_function('$a', '$a->add("avatar_error","<strong>".__("Ошибка при загрузке аватара:","simple-local-avatars")."</strong> ' . esc_attr($avatar['error']) . '");'));
}
return;
}
$this->avatar_delete($user_id);
update_user_meta($user_id, 'simple_local_avatar', array('full' => $avatar['url']));
} elseif (isset($_POST['simple-local-avatar-erase']) && $_POST['simple-local-avatar-erase'] == 1)
$this->avatar_delete($user_id);
}
function avatar_defaults($avatar_defaults) {
remove_action('get_avatar', array($this, 'get_avatar'));
return $avatar_defaults;
}
function avatar_delete($user_id) {
$old_avatars = get_user_meta($user_id, 'simple_local_avatar', true);
$upload_path = wp_upload_dir();
if (is_array($old_avatars)) {
foreach ($old_avatars as $old_avatar) {
$old_avatar_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $old_avatar);
@unlink($old_avatar_path);
}
}
delete_user_meta($user_id, 'simple_local_avatar');
}
}
$simple_local_avatars = new simple_local_avatars;
if (!function_exists('get_simple_local_avatar')):
function get_simple_local_avatar($id_or_email, $size = '80', $default = '', $alt = false) {
global $simple_local_avatars;
return $simple_local_avatars->get_avatar('', $id_or_email, $size, $default, $alt);
}
endif;
register_uninstall_hook(__FILE__, 'simple_local_avatars_uninstall');
function simple_local_avatars_uninstall() {
$simple_local_avatars = new simple_local_avatars;
$users = get_users_of_blog();
foreach ($users as $user)
$simple_local_avatars->avatar_delete($user->user_id);
delete_option('simple_local_avatars_caps');
}
Я пробовал много вариантов, но все они не сработали.
Не могли бы вы подсказать, какие части кода мне нужно скопировать в мой кастомный шаблон для фронтенда?
Большое спасибо.
Хорошо, спасибо. Но что насчет остального кода? Какой фрагмент кода мне нужно вставить между двумя сниппетами, которые вы дали?
Sergey
Хмм, ваш пользовательский фронтенд-шаблон, посмотрите http://wordpress.stackexchange.com/questions/9775/how-to-edit-a-user-profile-on-the-front-end/9786#9786
Bainternet
Спасибо за ссылку, но мне нужно только поле загрузки аватара. Можете указать, какой фрагмент из Simple Avatar Uploads мне использовать между двумя сниппетами кода?
Sergey
Нам нужно передавать вторые параметры в действия:
- Действие
edit_user_profileтребует объект пользователя Wordpress (мы берем его из класса WP_User) - Действие
edit_user_profile_updateтребует ID пользователя
Первое действие отображает поле загрузки и текущий аватар, а второе выполняет саму загрузку. Именно поэтому мы должны вызывать его после нажатия кнопки. Мы отслеживаем кнопку в начале кода, поэтому после отправки страница обновляется и аватар обновляется (в противном случае он отображается как битое изображение).
Вот моя настройка:
<?php if(isset($_POST['user_avatar_edit_submit']))
{
do_action('edit_user_profile_update', bbp_get_displayed_user_id());
}
?>
<form id="your-profile" action="<?php bbp_user_profile_edit_url( bbp_get_displayed_user_id() ); ?>" method="post">
<?php
$this_user = new WP_User(bbp_get_displayed_user_id());
do_action('edit_user_profile', $this_user);
?>
<input type="submit" name="user_avatar_edit_submit" value="OK"/>
</form>
<?php get_header();
global $user_ID;
if ($user_ID) {
$user_info = get_userdata($user_ID);
$id = $user_info->ID;
}
?>
<?php if(isset($_POST['user_avatar_edit_submit']))
{
do_action('edit_user_profile_update', $id);
}
?>
<form id="your-profile" action="" method="post">
<?php
$myAv = new simple_local_avatars();
$myAv->edit_user_profile($user_info);
?>
<input type="submit" name="user_avatar_edit_submit" value="OK"/>
</form>
Примечание редактора: Следующий фрагмент содержит часть исходного кода из плагина Simple Local Avatars.
<?php
global $current_user;
$user_id = get_current_user_id();
$user_last = get_user_meta($user_id);
$unserialize = unserialize($user_last['simple_local_avatar'][0]);
class Simple_Local_Avatarssss {
private $user_id_being_edited, $avatar_upload_error, $remove_nonce, $avatar_ratings;
public $options;
public function unique_filename_callback($dir, $name, $ext) {
$user = get_user_by('id', (int) $this->user_id_being_edited);
$name = $base_name = sanitize_file_name($user->display_name . '_avatar_' . time());
// убедимся, что нет конфликтов с существующими именами файлов
$number = 1;
while (file_exists($dir . "/$name$ext")) {
$name = $base_name . '_' . $number;
$number++;
}
return $name . $ext;
}
private function assign_new_user_avatar($url_or_media_id, $user_id) {
// удаляем старый аватар
$this->avatar_delete($user_id); // удаляем старые изображения, если успешно
$meta_value = array();
// устанавливаем новый аватар
if (is_int($url_or_media_id)) {
$meta_value['media_id'] = $url_or_media_id;
$url_or_media_id = wp_get_attachment_url($url_or_media_id);
}
$meta_value['full'] = $url_or_media_id;
update_user_meta($user_id, 'simple_local_avatar', $meta_value); // сохраняем информацию пользователя (перезаписывая старую)
}
public function avatar_delete($user_id) {
$old_avatars = (array) get_user_meta($user_id, 'simple_local_avatar', true);
if (empty($old_avatars))
return;
// если это была загруженная медиа, не стираем полный размер или не пытаемся стереть ID
if (array_key_exists('media_id', $old_avatars))
unset($old_avatars['media_id'], $old_avatars['full']);
if (!empty($old_avatars)) {
$upload_path = wp_upload_dir();
foreach ($old_avatars as $old_avatar) {
// определяем путь к файлу на основе директории загрузки
$old_avatar_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $old_avatar);
if (file_exists($old_avatar_path))
unlink($old_avatar_path);
}
}
delete_user_meta($user_id, 'simple_local_avatar');
delete_user_meta($user_id, 'simple_local_avatar_rating');
}
public function edit_user_profile_update($file, $user_id) {
$_FILES['simple-local-avatar'] = $file['file'];
// проверяем загруженные файлы
if (!empty($_FILES['simple-local-avatar']['name'])) :
// поддержка фронтенда (theme my profile и т.д.)
if (!function_exists('wp_handle_upload'))
require_once(ABSPATH . 'wp-admin/includes/file.php');
$this->user_id_being_edited = $user_id; // делаем user_id известным для функции unique_filename_callback
$avatar = wp_handle_upload($_FILES['simple-local-avatar'], array(
'mimes' => array(
'jpg|jpeg|jpe' => 'image/jpeg',
'gif' => 'image/gif',
'png' => 'image/png',
),
'test_form' => false,
'unique_filename_callback' => array($this, 'unique_filename_callback')
));
if (empty($avatar['file'])) { // обрабатываем ошибки
switch ($avatar['error']) {
case 'File type does not meet security guidelines. Try another.' :
$this->avatar_upload_error = __('Пожалуйста, загрузите корректный файл изображения для аватара.', 'simple-local-avatars');
break;
default :
$this->avatar_upload_error = '<strong>' . __('Произошла ошибка при загрузке аватара:', 'simple-local-avatars') . '</strong> ' . esc_html($avatar['error']);
}
return;
}
$this->assign_new_user_avatar($avatar['url'], $user_id);
endif;
// обрабатываем рейтинг
if (isset($avatar['url']) || $avatar = get_user_meta($user_id, 'simple_local_avatar', true)) {
if (empty($_POST['simple_local_avatar_rating']) || !array_key_exists($_POST['simple_local_avatar_rating'], $this->avatar_ratings))
// $_POST['simple_local_avatar_rating'] = key($this->avatar_ratings);
update_user_meta($user_id, 'simple_local_avatar_rating', $_POST['simple_local_avatar_rating']);
return 1;
}
}
}
if(isset($_POST['sub']))
{
$fname=$_FILES['file']['name'];
$ftype=$_FILES['file']['type'];
}
if(isset($_FILES['file']['name']) && !empty($_FILES['file']['name'])) {
$simple_local_avatars = new Simple_Local_Avatarssss;
$result = $simple_local_avatars->edit_user_profile_update($_FILES,$user_id);
if($result):
echo 'Обновлено';
endif;
}
?>
<form action="" method="POST" enctype="multipart/form-data">
<?php echo get_avatar($user_id, 96, $default, $alt); ?><br /><br />
<input type="file" name="file"><br /><br />
<input style="float: left;" type="submit" name="sub" value="Загрузить изображение">
</form>
Пожалуйста, добавляйте свой код правильно. Выделите весь код в редакторе и нажмите на значок {}. Это правильно добавит ваш код в блок кода. Также добавьте объяснение, что делает ваш код и как он работает.
Pieter Goosen
Также: если вы скопировали этот код откуда-то, вы должны указать/сослаться на источник и соблюдать его лицензию. Итак: это ваш код или код другого автора?
kaiser
@userabuser Спасибо, что подключился. Ты уверен насчёт части "to fit this question"?
kaiser