Skip to content

Instantly share code, notes, and snippets.

@nandomoreirame
Created August 19, 2019 02:07
Show Gist options
  • Save nandomoreirame/aeda5e3e3b7c6521019fa50730d33690 to your computer and use it in GitHub Desktop.
Save nandomoreirame/aeda5e3e3b7c6521019fa50730d33690 to your computer and use it in GitHub Desktop.
WP REST API send contact mail
<?php
add_action('rest_api_init', function () {
register_rest_route( 'contact/v1', 'send', [
'methods' => 'POST',
'callback' => 'api_send_contact_form'
]);
});
function api_send_contact_form( $request ) {
$params = $request->get_params();
$name = !empty( $params['name'] ) ? sanitize_text_field( trim( $params['name'] ) ) : '';
$email = !empty( $params['email'] ) ? sanitize_text_field( trim( $params['email'] ) ) : '';
$phone = !empty( $params['phone'] ) ? sanitize_text_field( trim( $params['phone'] ) ) : '';
$message = !empty( $params['message'] ) ? wp_kses_post( trim( $params['message'] ) ) : '';
$errors = [];
if (empty($name)) {
$errors[] = 'O nome é obrigatório!';
}
if ( empty( $email ) ) {
$errors[] = 'O email é obrigatório!';
}
if ( ! is_email( $email ) ) {
$errors[] = 'O email é inválido!';
}
if ( empty( $phone ) ) {
$errors[] = 'O telefone é obrigatório!';
}
if ( empty( $message ) ) {
$errors[] = 'A mensagem é obrigatória!';
}
if (count($errors)) {
return new WP_Error(422, 'contact_form_errors', [
'type' => 'danger',
'message' => 'Por favor confira os campos obrigatórios do formulário!',
'errors' => $errors
]);
}
$from_name = get_option('blogname');
$from_email = get_option('admin_email');
$subject = "[{$from_name}] novo contato do site!";
$body = "<p style='margin:0px;padding:0px;'><b>Nome</b>: {$name}</p>";
$body .= "<p style='margin:0px;padding:0px;'><b>Email</b>: {$email}</p>";
$body .= "<p style='margin:0px;padding:0px;'><b>Telefone</b>: {$phone}</p>";
$body .= "<p style='margin:0px;padding:0px;'><b>Mensagem</b>: {$message}</p>";
$headers[] = "Content-Type: text/html";
$headers[] = "charset=UTF-8";
$headers[] = "From: {$from_name} <{$from_email}>";
$headers[] = "Cco: Fernando Moreira <nandomoreira.me@gmail.com>";
$headers[] = "Reply-To: {$name} <{$email}>";
if ( wp_mail( $from_email, $subject, $body, $headers ) ) {
$response_data = [
'type' => 'success',
'message' => 'Email enviado com sucesso!',
// 'headers' => $headers,
'to' => $from_email,
'subject' => $subject,
'body' => $body,
];
$response = new WP_REST_Response($response_data);
$response->set_status(200);
return $response;
} else {
return new WP_Error( 422, 'contact_form_error', [
'type' => 'danger',
'message' => 'Desculpe, ocorreu um erro ao enviar o email.'
] );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment