top of page

wp_localize_script / pass dynamic variables to js files

  • Writer: سُلَيْمَان بْن دَاوُوْد
    سُلَيْمَان بْن دَاوُوْد
  • May 21, 2020
  • 1 min read

wp_localize_script is used to pass dynamic values to custom js files. The version is used in a way that it adds a timestamp to the modified time of js and this way the sites with heavy caching like WPEngine can automatically pick up latest code and end users wont face much caching issues.


This is how it looks on functions.php


	$theme_js_path = get_template_directory().'/js/developer.js';
    $js_ver        = filemtime( $theme_js_path );
	wp_register_script( 'developerjs', get_template_directory_uri() . '/js/developer.js', array('jquery'), $js_ver, true );
	$yup = array(
		'siteurl'     => site_url(),
		'adminurl'    => admin_url(),
		'ajaxurl'     => admin_url('admin-ajax.php'),
		'templateurl' => get_template_directory_uri(),
		'search_page' => get_field('search_page','option')
	);
	wp_localize_script( 'developerjs', 'yup', $yup );
	wp_enqueue_script( 'developerjs');

This is how it looks on developer.js


        jQuery.ajax({
            url    : yup.ajaxurl,
            type   : 'POST',
            data   : registrationdata,
                beforeSend: function() {
   
                },
                success: function(response) {              
                    responseobj = jQuery.parseJSON(response);
                    if (responseobj['flag'] == 'success') {
                        jQuery('#step-11').show();
                    }
                }
        });




Recent Posts

See All
Hide Upcoming Events

Hiding Upcoming Events can be relatively useful when you are using ACF fields to show Dates for an an Event The Following Snippet is an...

 
 
 

Comments


© 2020 by syednazrulhassan

bottom of page