Wp admin user edit php

edit_user( int $user_id )

Используется на user-edit.php и profile.php для управления и обработки параметров пользователя,паролей и т.д.

Parameters

(int) (Необязательно) ID пользователя.

Return

(int| WP_Error ) ID обновленного пользователя или WP_Error в случае сбоя.

Source

function edit_user( $user_id = 0 ) < $wp_roles = wp_roles(); $user = new stdClass; $user_id = (int) $user_id; if ( $user_id ) < $update = true; $user->ID = $user_id; $userdata = get_userdata( $user_id ); $user->user_login = wp_slash( $userdata->user_login ); > else < $update = false; > if ( ! $update && isset( $_POST['user_login'] ) ) < $user->user_login = sanitize_user( wp_unslash( $_POST['user_login'] ), true ); > $pass1 = ''; $pass2 = ''; if ( isset( $_POST['pass1'] ) ) < $pass1 = trim( $_POST['pass1'] ); > if ( isset( $_POST['pass2'] ) ) < $pass2 = trim( $_POST['pass2'] ); > if ( isset( $_POST['role'] ) && current_user_can( 'promote_users' ) && ( ! $user_id || current_user_can( 'promote_user', $user_id ) ) ) < $new_role = sanitize_text_field( $_POST['role'] ); // Если новая роль не может быть изменена вошедшим в систему пользователем, умирает с ошибкой. $editable_roles = get_editable_roles(); if ( ! empty( $new_role ) && empty( $editable_roles[ $new_role ] ) ) < wp_die( __( 'Sorry, you are not allowed to give users that role.' ), 403 ); > $potential_role = isset( $wp_roles->role_objects[ $new_role ] ) ? $wp_roles->role_objects[ $new_role ] : false; / * * Не позволяйте никому с 'promo_users' редактировать свою роль на что-то без него. * Суперадминистраторы мультисайтов могут свободно редактировать свои роли, у них есть все заглавные буквы. * / if ( ( is_multisite() && current_user_can( 'manage_network_users' ) ) || get_current_user_id() !== $user_id || ( $potential_role && $potential_role->has_cap( 'promote_users' ) ) ) < $user->role = $new_role; > > if ( isset( $_POST['email'] ) ) < $user->user_email = sanitize_text_field( wp_unslash( $_POST['email'] ) ); > if ( isset( $_POST['url'] ) ) < if ( empty( $_POST['url'] ) || 'http://' === $_POST['url'] ) < $user->user_url = ''; > else < $user->user_url = esc_url_raw( $_POST['url'] ); $protocols = implode( '|', array_map( 'preg_quote', wp_allowed_protocols() ) ); $user->user_url = preg_match( '/^(' . $protocols . '):/is', $user->user_url ) ? $user->user_url : 'http://' . $user->user_url; > > if ( isset( $_POST['first_name'] ) ) < $user->first_name = sanitize_text_field( $_POST['first_name'] ); > if ( isset( $_POST['last_name'] ) ) < $user->last_name = sanitize_text_field( $_POST['last_name'] ); > if ( isset( $_POST['nickname'] ) ) < $user->nickname = sanitize_text_field( $_POST['nickname'] ); > if ( isset( $_POST['display_name'] ) ) < $user->display_name = sanitize_text_field( $_POST['display_name'] ); > if ( isset( $_POST['description'] ) ) < $user->description = trim( $_POST['description'] ); > foreach ( wp_get_user_contact_methods( $user ) as $method => $name ) < if ( isset( $_POST[ $method ] ) ) < $user->$method = sanitize_text_field( $_POST[ $method ] ); > > if ( isset( $_POST['locale'] ) ) < $locale = sanitize_text_field( $_POST['locale'] ); if ( 'site-default' === $locale ) < $locale = ''; > elseif ( '' === $locale ) < $locale = 'en_US'; > elseif ( ! in_array( $locale, get_available_languages(), true ) ) < $locale = ''; > $user->locale = $locale; > if ( $update ) < $user->rich_editing = isset( $_POST['rich_editing'] ) && 'false' === $_POST['rich_editing'] ? 'false' : 'true'; $user->syntax_highlighting = isset( $_POST['syntax_highlighting'] ) && 'false' === $_POST['syntax_highlighting'] ? 'false' : 'true'; $user->admin_color = isset( $_POST['admin_color'] ) ? sanitize_text_field( $_POST['admin_color'] ) : 'fresh'; $user->show_admin_bar_front = isset( $_POST['admin_bar_front'] ) ? 'true' : 'false'; > $user->comment_shortcuts = isset( $_POST['comment_shortcuts'] ) && 'true' === $_POST['comment_shortcuts'] ? 'true' : ''; $user->use_ssl = 0; if ( ! empty( $_POST['use_ssl'] ) ) < $user->use_ssl = 1; > $errors = new WP_Error(); / * проверка того, что имя пользователя набрано * / if ( '' === $user->user_login ) < $errors->add( 'user_login', __( 'Error: Please enter a username.' ) ); > / * проверка того, что ник был набран * / if ( $update && empty( $user->nickname ) ) < $errors->add( 'nickname', __( 'Error: Please enter a nickname.' ) ); > / ** * Срабатывает до того, как пароль и поля подтверждения пароля проверяются на соответствие. * * @since 1.5.1 * * @param string $ user_login Имя пользователя. * @param string $ pass1 Пароль (передается по ссылке). * @param string $ pass2 Подтвержденный пароль (передается по ссылке). * / do_action_ref_array( 'check_passwords', array( $user->user_login, &$pass1, &$pass2 ) ); // Проверяем пустой пароль при добавлении пользователя. if ( ! $update && empty( $pass1 ) ) < $errors->add( 'pass', __( 'Error: Please enter a password.' ), array( 'form-field' => 'pass1' ) ); > // Проверяем "\" в пароле. if ( false !== strpos( wp_unslash( $pass1 ), '\\' ) ) < $errors->add( 'pass', __( 'Error: Passwords may not contain the character "\\".' ), array( 'form-field' => 'pass1' ) ); > // Проверка того, что пароль был набран дважды одинаково. if ( ( $update || ! empty( $pass1 ) ) && $pass1 != $pass2 ) < $errors->add( 'pass', __( 'Error: Passwords do not match. Please enter the same password in both password fields.' ), array( 'form-field' => 'pass1' ) ); > if ( ! empty( $pass1 ) ) < $user->user_pass = $pass1; > if ( ! $update && isset( $_POST['user_login'] ) && ! validate_username( $_POST['user_login'] ) ) < $errors->add( 'user_login', __( 'Error: This username is invalid because it uses illegal characters. Please enter a valid username.' ) ); > if ( ! $update && username_exists( $user->user_login ) ) < $errors->add( 'user_login', __( 'Error: This username is already registered. Please choose another one.' ) ); > / ** Этот фильтр задокументирован в wp-includes / user.php * / $illegal_logins = (array) apply_filters( 'illegal_user_logins', array() ); if ( in_array( strtolower( $user->user_login ), array_map( 'strtolower', $illegal_logins ), true ) ) < $errors->add( 'invalid_username', __( 'Error: Sorry, that username is not allowed.' ) ); > / * проверка адреса электронной почты * / if ( empty( $user->user_email ) ) < $errors->add( 'empty_email', __( 'Error: Please enter an email address.' ), array( 'form-field' => 'email' ) ); > elseif ( ! is_email( $user->user_email ) ) < $errors->add( 'invalid_email', __( 'Error: The email address is not correct.' ), array( 'form-field' => 'email' ) ); > else < $owner_id = email_exists( $user->user_email ); if ( $owner_id && ( ! $update || ( $owner_id != $user->ID ) ) ) < $errors->add( 'email_exists', __( 'Error: This email is already registered. Please choose another one.' ), array( 'form-field' => 'email' ) ); > > / ** * Запускается перед возвратом ошибок обновления профиля пользователя. * * @since 2.8.0 * * @param WP_Error $ errors Объект WP_Error (передается по ссылке). * @param bool $ update Является ли это обновлением пользователя. * @param stdClass $ user Пользовательский объект (передается по ссылке). * / do_action_ref_array( 'user_profile_update_errors', array( &$errors, $update, &$user ) ); if ( $errors->has_errors() ) < return $errors; > if ( $update ) < $user_id = wp_update_user( $user ); > else < $user_id = wp_insert_user( $user ); $notify = isset( $_POST['send_user_notification'] ) ? 'both' : 'admin'; /** * Срабатывает после создания нового пользователя. * * @since 4.4.0 * * @param int|WP_Error $user_id Идентификатор вновь созданного пользователя или WP_Error в случае сбоя. * @param string $notify Тип уведомления, которое должно произойти. См. * wp_send_new_user_notifications() для получения дополнительной информации. */ do_action( 'edit_user_created_user', $user_id, $notify ); > return $user_id; >

Uses

Фильтрует список запрещенных имен пользователей.

Читайте также:  nth-of-type

Сгорает после создания нового пользователя.

Извлекает глобальный экземпляр WP_Roles и при необходимости создает его.

Получить отфильтрованный список ролей пользователей,которые текущему пользователю разрешено редактировать.

Пожары перед полями пароля и подтверждения пароля проверяются на соответствие.

Возвращаются сообщения об ошибках перед обновлением профиля пользователя.

Возвращает, имеет ли текущий пользователь указанную возможность.

Получить все доступные языки на основе наличия *.mo файлов в данном каталоге.

Добавляет косые черты к строке или рекурсивно добавляет косые черты к строкам внутри массива.

Удаляет косые черты из строки или рекурсивно удаляет косые черты из строк в массиве.

Дезинфицирует строку из пользовательского ввода или из базы данных.

Выполняет esc_url () для использования базы данных или перенаправления.

Убедитесь,что электронное сообщение является действительным.

Дезинфицирует имя пользователя,удаляя небезопасные символы.

Получить информацию о пользователе по его идентификатору.

Получить список протоколов,разрешенных в атрибутах HTML.

Прекращает выполнение WordPress и отображает HTML-страницу с сообщением об ошибке.

Вызывает функции обратного вызова,которые были добавлены в хук действия,указывая аргументы в массиве.

Вызывает функции обратного вызова, которые были добавлены в обработчик фильтра.

Вызывает функции обратного вызова, которые были добавлены в хук действия.

Настраивает способы связи с пользователем.

Обновляет пользователя в базе данных.

Проверяет,является ли имя пользователя действительным.

Определяет,существует ли данное имя пользователя.

Определяет,существует ли данное электронное сообщение.

Вставляет пользователя в базу данных.

Получает идентификатор текущего пользователя.

Used By

Создает нового пользователя из формы «Пользователи», используя информацию $_POST.

Аякс-обработчик для добавления пользователя.

Changelog

WordPress 6.1

edit_term_link (строка $link = », строка $before = », строка $after = », int|WP_Term|null $term = null, bool $echo = true)

Источник

user_profile_picture_description

Filter Hook: Filters the user profile picture description displayed under the Gravatar.

admin_color_scheme_picker

Action Hook: Fires in the ‘Admin Color Scheme’ section of the user editing screen.

personal_options

Action Hook: Fires at the end of the ‘Personal Options’ settings table on the user editing screen.

profile_personal_options

Action Hook: Fires after the ‘Personal Options’ settings table on the ‘Your Profile’ editing screen.

user__label

Filter Hook: Filters a user contactmethod label.

show_user_profile

Action Hook: Fires after the ‘About Yourself’ settings table on the ‘Your Profile’ editing screen.

edit_user_profile

Action Hook: Fires after the ‘About the User’ settings table on the ‘Edit User’ screen.

additional_capabilities_display

Filter Hook: Filters whether to display additional capabilities for the user.

enable_edit_any_user_configuration

Filter Hook: Filters whether to allow administrators on Multisite to edit every user.

personal_options_update

Action Hook: Fires before the page loads on the ‘Your Profile’ editing screen.

edit_user_profile_update

Action Hook: Fires before the page loads on the ‘Edit User’ screen.

user_edit_form_tag

Action Hook: Fires inside the your-profile form tag on the user editing screen.

show_password_fields

Filter Hook: Filters the display of the password fields.

Источник

Оцените статью