Come posso inviare un form di contatti con jQuery e AJAX in WordPress?

Come posso inviare un form di contatti con jQuery e AJAX in WordPress?

Inviare un form di contatti con jQuery e AJAX è relativamente semplice in WordPress.

Possiamo definire il seguente codice in functions.php:


function my_send_contact() {
	
	// Campi del form
	
	$nome = trim( $_POST['nome'] );
	$cognome = trim( $_POST['cognome'] );
	$mail = trim( $_POST['mail'] );
	$oggetto = trim( $_POST['oggetto'] );
	$messaggio = trim( $_POST['messaggio'] );

	$errors = array(); // Array di messaggi di errore
	$output = ''; // Stringa HTML di output
	
	// Validazione

	if( empty( $nome ) ) {
		$errors[] = __( 'Nome è un campo richiesto', 'tema' );
	}

	if( empty( $cognome ) ) {
		$errors[] = __( 'Cognome è un campo richiesto', 'tema' );
	}

	if( !filter_var( $mail, FILTER_VALIDATE_EMAIL ) ) {
		$errors[] = __( 'E-mail non valida', 'tema' );	
	}

	if( empty( $oggetto ) ) {
		$errors[] = __( 'Oggetto è un campo richiesto', 'tema' );
	}

	if( empty( $messaggio ) ) {
		$errors[] = __( 'Messaggio è un campo richiesto', 'tema' );
	}

	if( count( $errors ) > 0 ) { // Ci sono errori
	
		$output = '<div id="validation-output">';
		foreach( $errors as $error ) {
			$output .= '<div class="message error">' . $error . '</div>';
		}
		$output .= '</div>';
		
	} else { // Invio e-mail
	
		$to = 'indirizzo e-mail';
		$subject = $oggetto;
		$body = strip_tags( $messaggio );
		$headers = 'From: ' . $nome . ' ' . $cognome . ' <' . $mail . '>' . "\r\n";
		wp_mail( $to, $subject, $body, $headers );

		$output = '<div id="validation-output">';
		$output .= '<div class="message success">' . __( 'Messaggio inviato con successo', 'tema' ) . '</div>';
		$output .= '</div>';
	}

	echo $output; // Restituisco la stringa HTML
	exit(); // Obbligatorio!
}

add_action( 'wp_ajax_my_send_contact', 'my_send_contact' ); // Utenti loggati
add_action( 'wp_ajax_nopriv_my_send_contact', 'my_send_contact' ); // Tutti i visitatori

Quindi con jQuery:


(function( $ ) {
	
	$(function() {
		var $contactForm = $( "#contact-form" );
		if( $contactForm.length ) {
			$contactForm.on( "submit", function( e ) {
				e.preventDefault();
				if( $( "#validation-output" ).length ) {
					$( "#validation-output" ).remove();	
				}
				var url = "http://" + location.host + "/wp-admin/admin-ajax.php";
				var data = "action=my_send_contact&" + $contactForm.serialize();
				
				$.post( url, data, function( output ){
					$contactForm.after( output );
					
				});
			});
		}
		
	});
	
})( jQuery );

Torna su