• Variables from WP to JS files

    Read more

    Server side :

    add_action('wp_enqueue_scripts', 'load_scripts');
    
    function load_scripts (){
    
    	$data = array(
    		'siteURL' => site_url()
    	);
    	$data_inline = 'const wpData = ' . json_encode( $data );
    
    	$handle = 'jsfile';
    
    	wp_enqueue_script(
    		$handle,
    		get_stylesheet_directory_uri() . '/assets/js/script.js',
    		array(),
    		filemtime( get_stylesheet_directory() . '/assets/js/script.js' ),
    		true
    	);
    
    	wp_add_inline_script( $handle, $data_inline );
    
    }

    Client side :

    const siteURL = wpData.siteURL;