Skip to navigation
How to add PHP data to the wp_enqueue_script JavaScript file.
07.10.25
How to add PHP data to the wp_enqueue_script JavaScript file. you can use wp_localize_script - addjsdata ``` Real Example: Passing Nonce + AJAX URL to JS function mg_enqueue_ajax_script() { wp_enqueue_script( 'mg-ajax', get_template_directory_uri() . '/assets/js/ajax.js', ['jquery'], '1.0', true ); wp_localize_script( 'mg-ajax', 'mgData', [ 'ajaxUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'mg_ajax_nonce' ), 'siteUrl' => get_site_url(), 'greeting' => __( 'Hello from PHP!', 'mg-textdomain' ), ] ); } add_action( 'wp_enqueue_scripts', 'mg_enqueue_ajax_script' ); Your JS will now have access to a global object: console.log(mgData.ajaxUrl); // "/wp-admin/admin-ajax.php" console.log(mgData.siteUrl); // "https://yoursite.com" Security Tip Use wp_create_nonce() and verify it in your AJAX handler. This protects against CSRF: check_ajax_referer( 'mg_ajax_nonce', 'nonce' ); ```
https://mehulgohil.com/blog/how-to-enqueue-scripts-in-wordpress/
Reply
Anonymous
Information Epoch 1762189978
Live free or die.
Home
Notebook
Contact us