Как правильно подключить обработчик форм в WordPress
Если вам необходимо интегрировать обработчик форм php в WordPress, вы можете воспользоваться следующим решением.
Создайте шаблон страницы в папке вашей темы и поместите в него свою разметку формы:
<?php
/* Template Name: My Form
*/
?>
<form method="POST">
....
<p class="form-submit">
<input name="updateuser" type="submit" id="updateuser" class="submit button" value="<?php _e('Update', 'profile'); ?>" />
<?php wp_nonce_field( 'update-user', 'wpgen' ) ?>
<input name="action" type="hidden" id="action" value="update-user" />
</p><!-- .form-submit -->
</form>
Как видите, мы не указываем action в форме, но добавляем в форму скрытое поле с произвольным именем и значением. Мы будем искать наличие этого поля, чтобы подключить обработчик.
Создайте страницу в админке и назначьте созданный выше шаблон. Затем поместите этот код в functions.php вашей темы.
add_action( 'init', function() {
if ( !empty( $_POST['action'] ) && $_POST['action'] == 'update-user' ) {
require get_stylesheet_directory() . '/user-profile.php'; // Replace user-profile.php with exact path to php file
}
} );
Для защиты передаваемых данных рекомендуется выводить в форме поле wp_nonce_field( 'update-user' );
с уникальным ключом, а в обработчике проверять соответствие if wp_verify_nonce( $_POST['_wpnonce'], 'update-user' )
Дополнительно, в обработчике вы можете проверять, что текущий метод именно POST if 'POST' == $_SERVER['REQUEST_METHOD']
и данные вам пришли с той ссылки, с которой вы ожидаете if $_POST['_wp_http_referer'] === '/'
Не забывайте, при обработке полученных данных преобразовывать символы <, >, &, ", '
в html сущности с помощью esc_attr()
и esc_url()
.
Сам файл с обработчиком user-profile.php
может выглядеть следующим образом
<?php
/**
* Template Name: User Profile
*
* Allow users to update their profiles from Frontend.
*
*/
/* Get user info. */
global $current_user, $wp_roles;
$error = array();
/* If profile was saved, update profile. */
if ( !empty($_POST) && 'POST' == $_SERVER['REQUEST_METHOD'] && wp_verify_nonce( $_POST['_wpnonce'], 'update-user' ) && $_POST['_wp_http_referer'] === '/' ) {
/* Update user password. */
if ( !empty($_POST['pass1'] ) && !empty( $_POST['pass2'] ) ) {
if ( $_POST['pass1'] == $_POST['pass2'] )
wp_update_user( array( 'ID' => $current_user->ID, 'user_pass' => esc_attr( $_POST['pass1'] ) ) );
else
$error[] = __('The passwords you entered do not match. Your password was not updated.', 'profile');
}
/* Update user information. */
if ( !empty( $_POST['url'] ) )
wp_update_user( array( 'ID' => $current_user->ID, 'user_url' => esc_url( $_POST['url'] ) ) );
if ( !empty( $_POST['email'] ) ){
if (!is_email(esc_attr( $_POST['email'] )))
$error[] = __('The Email you entered is not valid. please try again.', 'profile');
elseif(email_exists(esc_attr( $_POST['email'] )) != $current_user->id )
$error[] = __('This email is already used by another user. try a different one.', 'profile');
else{
wp_update_user( array ('ID' => $current_user->ID, 'user_email' => esc_attr( $_POST['email'] )));
}
}
if ( !empty( $_POST['first-name'] ) )
update_user_meta( $current_user->ID, 'first_name', esc_attr( $_POST['first-name'] ) );
if ( !empty( $_POST['last-name'] ) )
update_user_meta($current_user->ID, 'last_name', esc_attr( $_POST['last-name'] ) );
if ( !empty( $_POST['description'] ) )
update_user_meta( $current_user->ID, 'description', esc_attr( $_POST['description'] ) );
/* Redirect so the page will show updated info.*/
if ( count($error) == 0 ) {
//action hook for plugins and extra fields saving
do_action('edit_user_profile_update', $current_user->ID);
wp_redirect( $_POST['_wp_http_referer'] );
exit;
}
}
?>
За решение спасибо: