7 / 20
Click to copy a link of this slide to your clipboard.

Dissecting the Plugin: Enqueuing Scripts

  • We register and enqueue the script using the hook wp_enqueue_scripts – this is the proper hook to enqueue scripts on the frontend
    • Normally you would enqueue and localize the script inside of the shortcode itself (in WordPress 3.3.1 and greater), but because of event binding and how the content is loaded in this theme, I’ve got to enqueue and localize it here
  • wp_localize_script takes 3 params: the script handle, the JSON object name and the $args to localize
    • This must be called after the script being localized has been enqueued
    • Send over any data your script may need to access inside the $args array (nonces, localized text, URLs, etc)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
/**
* Loads all the stuff to make the plugin run.
*
* @since 1.0.0
*/
public function init() {
/** Load the plugin textdomain for internationalizing strings */
load_plugin_textdomain( 'sample-ajax-plugin', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ) );
add_shortcode( 'sample-ajax-plugin', array( $this, 'shortcode' ) );
}
/**
* Registers the scripts and styles for the plugin.
*
* @since 1.0.0
*/
public function scripts() {
/** Register and localize our script - we will enqueue it later */
wp_register_script( 'sample-ajax-plugin', plugins_url( '/js/ajax.js', __FILE__ ), array( 'jquery' ), '1.0.0', true );
$args = array(
'error' => __( 'An unknown error occurred. Please try again!', 'sample-ajax-plugin' ),
'nonce' => wp_create_nonce( 'sample-ajax-plugin-nonce' ),
'searching' => __( 'Searching...', 'sample-ajax-plugin' ),
'spinner' => admin_url( 'images/loading.gif' ),
'url' => admin_url( 'admin-ajax.php' )
);
wp_localize_script( 'sample-ajax-plugin', 'sample_ajax_raleigh', $args );
/** Register our style */
wp_register_style( 'sample-ajax-plugin', plugins_url( '/css/style.css', __FILE__ ) );
}
view raw gistfile1.php hosted with ❤ by GitHub