Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
[WordPress] HTML Data Attributes, JavaScript, and Databases
<select name="acme-options[name]" data-type="default" class="acme-options"
<!-- A set of options removed for brevity. -->
<input type="text" data-type="custom" name="acme-options[name]" value="" />
var data = {};
/* Assume that the element has been selected, we've stored
* a reference to it using $elem, and we're ready to send
* it across the wire to the server.
// Create a JavaScript object to send to the server.
data = {
'action': 'save_acme_data',
'data-type': $elem.attr( 'data-type' ),
'value': $elem.val()
// Use the WordPress Ajax API to send the data and parse the response.
$.post( ajaxurl, data, function( response ) {
response = $.parseJSON( response );
* An example function for saving information provided via Ajax to save
* to the database.
* The function will use the type of data being saved and its value to
* create the options key and value to save.
* The function will echo back a JSON response of the value that was saved
* to the database. This is done for example purposees only.
function save_acme_data() {
// If the data type or the value isn't set, then exit the function.
if ( ! isset( $_POST['data-type'] ) || ! isset( $_POST['value'] ) ) {
$type = sanitize_text_field(
$_POST['data-type'] // Input var okay.
$value = sanitize_text_field(
$_POST['value'] // Input var okay.
update_option( "acme_$type", $value );
echo json_encode( get_option( "acme_$type", '-1' ) );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment