Skip to content

Instantly share code, notes, and snippets.

@JayWood
Last active March 24, 2016 13:38
Show Gist options
  • Save JayWood/aa8d93b0ebca91e355c2 to your computer and use it in GitHub Desktop.
Save JayWood/aa8d93b0ebca91e355c2 to your computer and use it in GitHub Desktop.
Sending shortcode attributes to JS
// Basic linear javascript for example_class ajax
/**
* Ajax Success Handler
* @param {obj} data Response Object
* @return {null}
*/
var ajaxSuccess = function( data ) {
if ( window.console ) {
window.console.log( data );
}
}
/**
* Ajax Call
* @param {event} evt click event
* @return {null}
*/
var doAjaxStuffs = function( evt ) {
evt.preventDefault();
// Now get the closest hidden span
var atts_obj = jQuery( this ).closest( '.encoded-atts' );
// Simple check to make sure we have what we need
if ( 0 === atts_obj.length ) {
return;
}
// Now use the data() method to grab any data-* items based on key
var atts = atts_obj.data( 'encoded-atts' );
jQuery.post( someAjaxURL, {
action: 'get_value',
ajax_atts: atts, // This is how you get your attributes over there
}, ajaxSuccess );
}
jQuery( 'body' ).on( 'click', '.some-clicky-class', doAjaxStuffs );
<?php
class example_class {
private $options = array(); //(array)get_option(KEY); … where KEY is valid
public function __construct() {
add_action( ‘wp_ajax_nopriv_get_value’, array( $this, ‘get_value_handler’) );
add_action( ‘wp_ajax_get_value’, array( $this, ‘get_value_handler’) );
add_shortcode(‘mycode’, array( $this, ‘display_func’ ));
}
function display_func( $atts, $content ) {
$this->options = (array) get_option( $atts['some_attribute_key'] ); // Note Key depends on the short code parms
// Encode attributes for use in
$json_atts = json_encode( $atts );
$output = ''; // Some basic output
// Stores the JSON Atts in the shortcode's HTML output
$output .= '<span class="hidden encoded-atts" data-encoded-atts="' . $json_atts . '"></span>';
// More output stuffs if need be
// ...
return $output;
}
function get_value_handler() {
$nonce = $_REQUEST[‘ajaxNonce’]; // and verify, etc
// Decode your attributes into an array/obj depending on what you need
$sc_atts = json_decode( $_REQUEST['ajax_atts'] );
echo “options: ” . $this->options;
// at this point $this->options is set to whatever is in the constructor.
// since the options value depends on short code options, I load them in display_func
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment