I need a Clear Explanation on wp_enqueue_script and wp_localize_script
wp_enqueue_script( 'custome.js',PLUGIN_URL.'/js/custome.js');
wp_localize_script( 'ajax-script', 'my_ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script will include a Javascript file into your page or application. In Javascript file you may need to access few PHP variables or few Values that set from the your WordPress Pages. As example, when AJAX called in WordPress, it basically call a single URL that is "/wp-admin/admin-ajax.php", so you can access this URL from js file by hardcoding like :
var ajax_url="<site url>/wp-admin/admin-ajax.php";
So if you moved the code into different domain, you need to change the code in ajavscript, which usually forgotten. The solution is to make this URL dynamic so it react same with any URL. The code :
wp_localize_script( 'ajax-script', 'my_ajax_object',array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
is actually sending the AJAX URL using a variable named "ajax_url" with an object named "my_ajax_object". So you can access the AJAX URL in javascript file. Like :
var ajax_url=my_ajax_object.ajax_url;
Now if you need to send more values you can use same way :
wp_localize_script( 'ajax-script', 'my_ajax_object',array( 'ajax_url' => admin_url( 'admin-ajax.php' ),'your_name'=>'Tristup' ) );
In Javascript File :
console.log(my_ajax_object.your_name);
Hope it help you to understand the localized script, if any doubts please reply to this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With