Javascript in WordPress: The Ultimate Cheat Sheet

Published 9th September 2013

Include Scripts (Front end)

function prefix_register_scripts() { wp_register_script( $handle, $src, $deps, $ver, $in_footer ); } add_action( 'init', 'prefix_register_scripts' ); function prefix_enqueue_scripts() { wp_enqueue_script( $handle ); } add_action( 'wp_enqueue_scripts', 'prefix_enqueue_scripts' );

Include Scripts (Admin)

function prefix_register_scripts() { wp_register_script( $handle, $src, $deps, $ver, $in_footer ); } add_action( 'admin_init', 'prefix_register_scripts' ); function prefix_enqueue_scripts( $hook ) { wp_enqueue_script( $handle ); // Enqueue on specific page if( $hook == 'edit.php' ) { wp_enqueue_script( $handle ); } } add_action( 'admin_enqueue_scripts', 'prefix_enqueue_scripts' );

AJAX

function prefix_enqueue_scripts() { wp_enqueue_script( $my-js-with-ajax ); // Setup vars to use in JS wp_localize_script( $handle, $object_name, array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( $action ) ) ); } add_action( 'admin_enqueue_scripts', 'prefix_enqueue_scripts' );

Then in your Javascript (jQuery) file you can use the variables like this:

$.post(object_name.ajax_url, { action: 'prefix_ajax_action', nonce: object_name.nonce }, function(data){ //... });

Further Reading