Created
December 17, 2024 16:58
-
-
Save gonzalesc/8d15c721785510d985eff5564208e4b5 to your computer and use it in GitHub Desktop.
Send PHP variables to script JS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Send php variables to js | |
* @package LetsGodev\MuPlugins | |
* @since 1.0 | |
* @description : use letsgo_vars.ajax_url in script js | |
*/ | |
add_action( 'wp_enqueue_scripts', 'sendVarsToScripts' ); | |
/** | |
* Send php variables to js | |
* @return void | |
*/ | |
function sendVarsToScripts(): void { | |
// Register a JS script | |
wp_register_script( | |
'letsgo-js', | |
plugins_url( 'resources/assets/scripts/letsgo.js', __FILE__ ), | |
[ 'jquery' ], | |
wp_get_wp_version(), | |
[ 'in_footer' => true ] | |
); | |
// Include a JS script | |
wp_enqueue_script( 'letsgo-js' ); | |
// Send PHP | |
wp_localize_script( 'letsgo-js', 'letsgo_vars', [ | |
'ajax_url' => admin_url( 'admin-ajax.php' ), | |
'ajax_nonce' => wp_create_nonce( 'letsgo-nonce' ), | |
'site_url' => get_site_url(), | |
] ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment