wp ajax - 核心功能 wpnonce 检查
functions.php :
function rm_init_js() {
wp_enqueue_script( 'custom-ajax-script', get_template_directory_uri() . '/js/ajax.js', array( 'jquery', 'wp-util' ), '1.0', true );
// pass custom variables to JS
wp_localize_script( 'custom-ajax-script', 'BEJS', array(
'action' => 'custom_action',
'nonce' => wp_create_nonce( 'test-nonce' )
) );
}
add_action( 'wp_enqueue_scripts', 'rm_init_js' );
function rm_ajax_handler() {
check_ajax_referer( 'test-nonce' );
extract( $_POST );
$data = compact( 'first_name', 'last_name', 'email' );
foreach ( $data as $name => $value ) {
switch ( $name ) {
case 'first_name':
case 'last_name':
$data[ $name ] = ucfirst( sanitize_user( $value ) );
break;
case 'email':
$data[ $name ] = sanitize_email( $value );
break;
}
}
$userID = email_exists( $data['email'] );
if ( ! $userID ) {
wp_send_json_error( sprintf( __( 'Something went wrong! %s try again!', 'textdomain' ), $data['first_name'] . ' ' . $data['last_name'] ) );
}
wp_update_user( array(
'ID' => $userID,
'display_name' => $data['first_name'] . ' ' . $data['last_name'],
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
) );
wp_send_json_success( sprintf( __( 'Welcome Back %s', 'textdomain' ), $data['first_name'] . ' ' . $data['last_name'] ) );
}
add_action( 'wp_ajax_custom_action', 'rm_ajax_handler' );
add_action( 'wp_ajax_nopriv_custom_action', 'rm_ajax_handler' );
ajax.js
;(function() {
wp.ajax.post(BEJS.action, {
first_name: 'john',
last_name: '%65doe',
email: 'john.doe@example.com',
_ajax_nonce: BEJS.nonce
}).done( function( response ) {
alert(`Success: ${response}`);
}).fail( function( response ) {
alert(`Error: ${response}`);
});
})();