JavaScript in PHP

Lately I’ve been seeing a few themes that like to include and devote an entire file to JavaScript. There is a reason I don’t like this. Biggest one is because it creates bad practices. Yes, I understand you want to pass some variables between the two languages but there are better ways. What’s super cool is that WordPress has this amazing function that theme, and plugin, developers can use.

Enter: wp_localize_script

It’s a great and amazing function. So the question is, when should it be used? A great example would be ( dare I say ) a slider. Yes, I know. The dreaded sliders. People love them but often have to make changes to files that could be lost when the theme updates.

Recently I was fiddling around with bxslider for fun. Neat little library and fun to use when you get the hang of it too. Really customizable with several options.

So, on to the code portion!

The first thing we do is to create our settings. I highly encourage the use of the customizer when possible so we will use it as our starting point. In this example, we create a setting for the slider’s autoplay setting. A simple setting that the user can turn on or off. The slider does have many more options that you can configure but we will stick to simplicity for this example.

$wp_customize->add_section( 'demo-slider', array(
	'title' => __( 'Slider options', 'dademo' ),
	'description' => __( 'Set the slider\'s options', 'dademo' ),
	'priority' => 130
	) );
$wp_customize->add_setting( 'demo-slider-auto', array(
	'default' => false,
	'sanitize_callback' => 'demo_checkbox'
	) );
$wp_customize->add_control( 'demo-slider-auto-setting', array(
	'label' => __( 'Autoplay', 'dademo' ),
	'section' => 'demo-slider',
	'settings' => 'demo-slider-auto',
	'type' => 'checkbox'
	) );

Please note, I have not included the demo_checkbox function. That is a simple function that checks for true or false which you can add yourself. From there we enqueue our scripts and possible styles if you are using or wanting any.

wp_enqueue_script( 'slider-js', get_template_directory_uri() . '/js/jquery.bxslider.min.js', array( 'jquery' ), null );
wp_enqueue_style( 'slider', get_template_directory_uri() . '/css/jquery.bxslider.css', null );
wp_enqueue_script( 'demo-js', get_template_directory_uri() . '/js/demo.js', array( 'slider-js','jquery' ), null );

Now, the only thing that is missing is to use wp_localize_script to create our JavaScript object. Yes, you read that right: JavaScript object.

In order to do that we first have to look at the function itself and see how it works. So let’s break it down a little, shall we?

Parameter, the first

The first parameter that we pass to it is the JavaScript file that we want to localize. The key thing to remember is that the script has to be already registered or enqueued, otherwise it will not create the object. For our example, we would use it after our slider is enqueued:

wp_enqueue_script( 'slider-js', get_template_directory_uri() . '/js/jquery.bxslider.min.js', array( 'jquery' ), null );
wp_enqueue_script( 'demo-js', get_template_directory_uri() . '/js/demo.js', array( 'slider-js','jquery' ), null );
wp_localize_script( 'slider-js', 'demoObj', $jsObj );

Our new object

Second, is the name of the JavaScript object that is created and used in our external JavaScript file or files. In this case it would be the demo-js file. Behind the scenes the function creates the variable and uses wp_json_encode to create our object. For this example the newly created object is called demoObj. It can be anything you want but ideally you want to prefix it so it won’t interfere with any other objects or even plugins. Yes, plugins.

Our user settings

Finally, we pass an associative array to the function. This is where your user settings will reside. In this example you can see we create a simple property of auto for our newly created JavaScript object. We then pass the array to wp_localize_script so it can be output in our header’s <head> element and used in our JavaScript files.

$slider = array();
$slider['auto'] = get_theme_mod( 'demo-slider-auto', false );
$jsObj = apply_filters( 'demo_slider', $slider);

wp_localize_script( 'slider-js', 'demoObj', $jsObj );

Yes, I like using filters when possible that way a child theme can override it. You don’t have to do it but it is something to think about. As I mentioned, behind the scenes, wp_localize_script will create the JavaSCript object and output it in the <head> section. The <head> output will look a little like the following snippet.

<script type='text/javascript'>
/* <![CDATA[ */
var demoObj = {"auto":""};
/* ]]> */
</script>

As you can see it creates a global variable that can be used in any JavaScript file. Since it is a simple example it created only one JavaScript property for the demoObj object.

What next?

Great! We have our newly created JavaScript object but how do we use it? What’s super neat is we can use it like any other JavaScript object when we get a property.

jQuery( document ).ready( function( $ ){
	$( '.gallery' ).bxSlider( {
		'auto': demoObj.auto,
		// alternatively use bracket notation
		// 'auto': demoObj['auto'],
	});
})

That’s great for settings, what happens when you are dealing with interaction or even text? A simple example would be adding a small dialogue when a user adds an item to a shopping cart. With wp_localize_script you can do it. Pippin has great example of this in his article.

So go explore and break things!

Published by

Jose

Born in El Salvador. Loves to read, write, draw, paint, build, test, typography, hike, photography, art, design, sewing, and many other things.