Alright, there’s a few things that isn’t standardized WordPress so I’ve put together a minimal script which I’ll explain piece by piece. Hopefully clear things up for you by the time you get to the end.
HTML Form
Below is a very simple HTML form. We’re going to use javascript to listen for submission and stop it from actually refreshing the page but that will be later.
<form id="um_form" method="POST">
<p>
<label for="um_key">
User Meta Value:
<input type="text" name="um_key" id="um_key" value="" style="width:100%;" />
</label>
<input type="submit" value="Submit" />
</p>
</form>
We’re $_POST
ing the form but you could also $_GET
the form if you’d like. In this situation I don’t think it matters.
Enqueue our scripts
So WordPress has a hook which you can use to enqueue styles and scripts in their proper places ( header or footer ) called wp_enqueue_scripts
. Using this we can localize our script and pass a variable ( or two if you’d like ) to our javascript, specifically the ajax_url
. Doing that looks something like this:
/**
* Enqueue our Scripts and Styles Properly
*/
function theme_enqueue() {
$theme_url = get_template_directory_uri(); // Used to keep our Template Directory URL
$ajax_url = admin_url( 'admin-ajax.php' ); // Localized AJAX URL
// Register Our Script for Localization
wp_register_script(
'um-modifications', // Our Custom Handle
"{$theme_url}/scripts/um-modifications.js", // Script URL, this script is located for me in `theme-name/scripts/um-modifications.js`
array( 'jquery' ), // Dependant Array
'1.0', // Script Version ( Arbitrary )
true // Enqueue in Footer
);
// Localize Our Script so we can use `ajax_url`
wp_localize_script(
'um-modifications',
'ajax_url',
$ajax_url
);
// Finally enqueue our script
wp_enqueue_script( 'um-modifications' );
}
add_action( 'wp_enqueue_scripts', 'theme_enqueue' );
The above code is heavily commented so please read through the code comments if something doesn’t make sense. This would go into your functions.php
file.
Our Javascript / JQuery
Since I wanted to keep it simple, In this example we’re only processing one meta_value but you could just as easily passed multiple meta_values
to the data object, referencing them in your PHP by $_POST
index which we’ll see later. The below lies in a scripts directory, theme-name/scripts/um-modifications.js
and is also heavily commented:
// Declare our JQuery Alias
jQuery( 'document' ).ready( function( $ ) {
// Form submission listener
$( '#um_form' ).submit( function() {
// Grab our post meta value
var um_val = $( '#um_form #um_key' ).val();
// Do very simple value validation
if( $( '#um_form #um_key' ).val().length ) {
$.ajax( {
url : ajax_url, // Use our localized variable that holds the AJAX URL
type: 'POST', // Declare our ajax submission method ( GET or POST )
data: { // This is our data object
action : 'um_cb', // AJAX POST Action
'first_name': um_val, // Replace `um_key` with your user_meta key name
}
} )
.success( function( results ) {
console.log( 'User Meta Updated!' );
} )
.fail( function( data ) {
console.log( data.responseText );
console.log( 'Request failed: ' + data.statusText );
} );
} else {
// Show user error message.
}
return false; // Stop our form from submitting
} );
} );
AJAX PHP Callback / Handler / Action
Finally, The actual processing! Important things to note are the hooks at the end of this function:
- wp_ajax_nopriv_{your_ajax_action_name_here} – allows us to use ajax on the front end
- wp_ajax_{your_ajax_action_name_here} – allows us to use ajax period.
Here we can get the current user and update their user_meta
or even the User Object if we wanted to.
/**
* AJAX Callback
* Always Echos and Exits
*/
function um_modifications_callback() {
// Ensure we have the data we need to continue
if( ! isset( $_POST ) || empty( $_POST ) || ! is_user_logged_in() ) {
// If we don't - return custom error message and exit
header( 'HTTP/1.1 400 Empty POST Values' );
echo 'Could Not Verify POST Values.';
exit;
}
$user_id = get_current_user_id(); // Get our current user ID
$um_val = sanitize_text_field( $_POST['first_name'] ); // Sanitize our user meta value
$um_user_email = sanitize_text_field( $_POST['user_email'] ); // Sanitize our user email field
update_user_meta( $user_id, 'first_name', $um_val ); // Update our user meta
wp_update_user( array(
'ID' => $user_id,
'user_email' => $um_user_email,
) );
exit;
}
add_action( 'wp_ajax_nopriv_um_cb', 'um_modifications_callback' );
add_action( 'wp_ajax_um_cb', 'um_modifications_callback' );
Hopefully this makes it easier for you to understand and visualize. Should you have any questions, comment below!