rtCamp notes, day 33 of undefined

Localisation in a JS

How do we localize a JS file?

As we cannot directly implement localisation in a JS file, wordpress provide us with a workaround to do that. If we need to pass a variable from PHP to JS that can be also done by this way.

Function: wp_localize_script()

This function takes the handle_name as its first parameter to configure itself for the specified script handle.

The second parameter is taken as the object name or we can say the variable name for javascript.

The third parameter is our l10n array or we can say our localization array or we can say our data to be passed to javascript.

Now, How it works?

It json encodes the data we provide it and before the enqueuing of the script to the front end the data is printed as a JS object so that we can use that object to access this data in our JS code.

$translation_array = array(
	'some_test_data' => __( 'Some random data', 'movie-library' ),
	'test' => 'some other data',
	'test-array' => array( 'Some', 'Test', 'Data' ),
);
wp_localize_script( 'custom-image-gallery', 'test_data', $translation_array );

For example, what this code does is that it prints this data into the front end

Later on we can use this test_data in our JS file to access the data we want.

MID DAY QnA: -> Interesting question -> How to add default widgets in a sidebar programmatically?

The widget information for a sidebar is stored under the wp_options table.
To fetch the current sidebar information we can run the below code

$sidebars_widgets = get_option( 'sidebars_widgets', array() );

This would return us an array which has the information as

[sidebar_id] => Array( Widget ids )

To add default widgets to a sidebar, we must know our sidebar id to which we must add the widget and the widget id to be added.
For example, our sidebar id is test-sidebar and our widget id is search-1
To add this we can use the following code below

$sidebar_id = 'test-sidebar';
$widget_id = 'search-1';

$sidebars = get_option( 'sidebars_widgets' );

$sidebars[ $sidebar_id ][] = $widget_id;

update_option( 'sidebars_widgets', $sidebars );

This would insert out widget id to the sidebar array and wordpress will use that widget for our sidebar.

Another point to add in this, to get a list of the widgets in our site we can access the $wp_registered_widgets and print it.

Leave a Reply

Your email address will not be published. Required fields are marked *