Software Developer

Send Localized PHP variables to jQuery

This page is in the Code Graveyard where I lay to rest snippets of code that I don't use anymore. Some have lost their usefulness due to the evolving nature of the web, while others have been replaced with better code. "Be Ye Warned!"

This was my way of localizing jQuery strings:
1. Set a variable for the localized string in PHP
2. Set that as a jQuery var, and send/hack it up to the head inside my wp_enqueue_scripts function right above the line to enqueue the .js script that needs to use the variable.

My method, as is below, is still useful and works outside of WordPress. But WordPress has made this obsolete with its built-in function: wp_localize_script( $handle, $object_name, $l10n ).

My old way, before learning about wp_localize_script():

	/**
	 * 12.10 Set localized php vars for js
	 */
	$env = __('The email address provided is not valid.', 'smartestb');
	$na = __('Bla bla bla. Some silly message.', 'smartestb');
	$hu = __('You must confirm that you are human.', 'smartestb');
	$wnv = __('The website provided is not valid. Be sure to include', 'smartestb');
			
	 // deliver the vars to js
	?>
	<script>
	var localized_errors = {
		email : "<?php echo $env ?>",
		name : "<?php echo $na ?>",
		human : "<?php echo $hu ?>",
		website : "<?php echo $wnv ?>"
	}
	</script>
<?php

By

We've One Response

Questions and Comments are Welcome

Your email address will not be published. All comments will be moderated.

Please wrap code in "code" bracket tags like this:

[code]

YOUR CODE HERE 

[/code]