Skip to content

Instantly share code, notes, and snippets.

@tommcfarlin
Last active November 18, 2016 22:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommcfarlin/8e7e93ba687e30e903875290377471ba to your computer and use it in GitHub Desktop.
Save tommcfarlin/8e7e93ba687e30e903875290377471ba to your computer and use it in GitHub Desktop.
[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. -->
</select>
<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 );
});
<?php
/**
* 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'] ) ) {
return;
}
$type = sanitize_text_field(
wp_unslash(
$_POST['data-type'] // Input var okay.
)
);
$value = sanitize_text_field(
wp_unslash(
$_POST['value'] // Input var okay.
)
);
update_option( "acme_$type", $value );
echo json_encode( get_option( "acme_$type", '-1' ) );
wp_die();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment