Skip to content

Instantly share code, notes, and snippets.

@petenelson
Last active June 1, 2023 16:43
Show Gist options
  • Save petenelson/b162e2e15a3da7b868138c8d57ce25ce to your computer and use it in GitHub Desktop.
Save petenelson/b162e2e15a3da7b868138c8d57ce25ce to your computer and use it in GitHub Desktop.
WordPress Localize Script Example
<?php
add_action( 'wp_enqueue_scripts', 'add_localized_js_data' );
function add_localized_js_data() {
wp_enqueue_script( 'my-frontend-script-handle', 'url to my frontend Javascript', array( 'jquery' ) );
$data = array(
'ajax_url' = admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'my-frontend-script-handle, 'My_Frontend_Data', $data );
/*
Now in your frontend Javascript code, you can access My_Frontend_Data.ajax_url to
get the URL to admin-ajax.
*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment