-
-
Save tommcfarlin/8e7e93ba687e30e903875290377471ba to your computer and use it in GitHub Desktop.
[WordPress] HTML Data Attributes, JavaScript, and Databases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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="" /> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 ); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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