Translate javascript with WordPress built-in localization API for static strings

I have been trying to implement the translation to a couple of strings in a .js file but nothing has worked. First try to do it like I do in php, in the .js file add this variable var __ = wp.i18n.__; and I put the strings like __( 'Hello World', 'text-domain'), but it didn't work. After looking for information about it, I found a post where they talk about passing the translated strings with wp_localize_script something like that. // …
Category: Web

Add action hook into wp_localize_script

Is it possible to add an action hook via wp_localize_script, so I can position where I want the hook to run in HTML markup that is made in the JavaScript? So something like: $data = array ( 'ng_slicknav' => array( 'ng_slicksearch' => home_url( '/' ), 'ng_slicknav_closedsymbol' => esc_html( $options['ng_slicknav_closedsymbol'] ), 'ng_slicknav_hook' => do_action( 'myplugin_after_hook' ), ), ); // Add filter $data = apply_filters( 'ng_slicknav_slickNavVars', $data ); // Pass PHP variables to jQuery script wp_localize_script( 'slicknav-init', 'slickNavVars', $data ); wp_enqueue_script( 'slicknav-init' …
Category: Web

Integrating PHP into Javascript to display map markers with Google API - problem with wp_localize

I would display Google maps markers on custom site temple with Google API maps. I do everything like this post: Integrating PHP into Javascript to display map markers with Google API But a console gives me an error, I don't know where I can look for the error. (index):774 Uncaught (in promise) ReferenceError: storeData is not defined at initMap ((index):774) at js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQU&callback=initMap:123 at js?key=AIzaSyAg-GBNbwLWCxiN-UI-0COkr1bgAKpXjQU&callback=initMap:123 I think the WordPress first try to use wp_localize, then load jquery. Or Wordpress don't know …
Category: Web

WordPress wp_localize_script nonce and ajax URL

I'm making an Ajax call in an Elementor site, and I'd like to use a nonce while doing it. Since my code is really simple, I didn't create a new JS file for it placed in Elementor's HTML widget, and I handle the request in the functions.php file. I realized that the best way is to use wp_localize_script to make both the nonce and the Ajax URL available in the client side, but the function is asking for a file …
Category: Web

Ajax is not defined

Stack Exchange long time listener, first time caller. I have found examples on the developer.wordpress site but I have been still struggling. Localizing scripts: wp_localize_script() In my theme's functions.php file, I have: function wp_my_ajax_script() { wp_localize_script( 'ajax_handle_agent_search', 'myAjax', admin_url( 'admin-ajax.php' )); wp_enqueue_script( 'ajax_handle_agent_search' ); } add_action( 'wp_enqueue_scripts', 'wp_my_ajax_script' ); And on my page, I've added a HTML code wdiget that contains: <script> jQuery(document).ready( function() { console.log("Document loaded"); jQuery("#searchButton").click( function(e) { console.log("Search button clicked"); console.log("Ajax: " . myAjax); e.preventDefault(); var zipCode …
Category: Web

How can I get user data into a javascript object?

I have the code below in my functions.php file. However, when I try to access the variable theUser in my custom.js file it comes back as undefined. Functions.php: function theme_scripts() { global $current_user; $current_user = wp_get_current_user(); wp_enqueue_script( 'theme-script', get_stylesheet_directory_uri() . '/assets/js/custom.js', array( 'jquery' ), '', true ); wp_localize_script( 'theme-script', 'theUser', array ( 'username' => $current_user, ) ); } add_action( 'wp_enqueue_scripts', 'theme_scripts' ); Custom.js: var theUser; var userName = theUser.username.data.display_name; var userEmail = theUser.username.data.user_email; console.log(theUser);
Category: Web

How to add ajax url to js using wp_add_inline_script()?

I usually enable ajax in a js script by using wp_localize_script like this wp_localize_script( 'map-scripts', 'ajax_info', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); but now I see it is best practice to use wp_add_inline_script, which I find harder to use. I am not able to pass an array with this method. I tried the following but it does not look the same: $ajax_arr = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ); $ajax_json = json_encode($ajax_arr); $ajax_info = 'ajax_info = '.json_encode($ajax_json).';'; …
Category: Web

Setting HTML properties in a Gutenberg plugin using WordPress settings

I want to set the maxlength property on a TextControl I define in a Gutenberg plugin. This length is to be set from a setting in my WordPress plugin (the one that loads the Gutenberg plugin). I attempted the standard approach of passing PHP data to JavaScript (using wp_localize_script, discussed for example here), but I wonder if there is a better way to do this, especially with the work that has gone into Gutenberg, than continuing to misappropriate a translation …
Category: Web

Localization of JavaScript which is only used in one page

Environment: WordPress 5.8 WPML: 4.4.10 DIVI: 4.9.4 What I am trying to achieve? I have a JavaScript validation script which should validate input on the registration page. This script shows error messages. I want two things: the strings should be managed/translated using WPML the script should only be embedded in the registration page What did I already achieve? I added the following script to functions.php of my theme. add_action('wp_enqueue_scripts', function() { // Register the script wp_register_script( 'register-validation-js', '/wp-content/themes/agreedo/js/register.js' ); // …
Category: Web

localize_script but data changes dependent on product ID

I currently have this code in my functions.php file. $dataToBePassed = array(); add_action( 'wp_enqueue_scripts', function() { $handle = 'three-d-scripts'; $src = get_stylesheet_directory_uri() . '/src/scripts/three-d-scripts.js'; $deps = []; $version = '1.0.0'; wp_enqueue_script( $handle, $src, $deps, $version, true ); } ); wp_localize_script( 'three-d-scripts', 'php_vars', $dataToBePassed ); What I am wanting to do is change the contents of dataToBePassed dependent on the product ID of the currently view products is this possible? I have tried, global $product; $product->get_id(); but this returns NULL as …
Category: Web

Passing boolean values with wp_localize_script

I am using wp_localize_script to pass a couple of values from my theme options to a javascript file. First I got the values from my theme options: $options = get_option('theme'); $flex_auto = $options["slide-auto"]; $flex_animation = $options["slide-animation"]; $flex_direction = $options["slide-direction"]; Then I used wp_localize_script to create my array of values. wp_enqueue_script('flexslider'); wp_localize_script('flexslider', 'flex_vars', array( 'flex_auto' => $flex_auto, 'flex_animation' => $flex_animation, 'flex_direction' => $flex_direction ) ); In my javascript file I did this: var $anim = flex_vars.flex_animation; var $auto = flex_vars.flex_auto; var …
Category: Web

wp_add_inline_script not adding when script_loader_tag filtered

I'm trying to add the new GA4 code to an existing site, and there seems to be some conflict / ordering issue between script_loader_tag filters and wp_add_inline_script. My functions.php looks thusly: ... // Enqueue scripts function cwr_enqueue_scripts() { wp_enqueue_script('cwr-google-analytics', get_stylesheet_directory_uri() . '/js/ga.js', array(), '1.0.3'); wp_add_inline_script('cwr-google-analytics', "ga('create', " . "'" . CWR_GAUA_ID . "', 'auto');ga('send', 'pageview');"); wp_enqueue_script('cwr-google-gtag', "https://www.googletagmanager.com" . "/gtag/js?id=" . CWR_GA4_ID, array(), null); wp_add_inline_script('cwr-google-gtag', "window.dataLayer = " . "window.dataLayer || [];" . "function gtag(){dataLayer.push(arguments);} gtag('js'," . "new Date()); gtag('config', '" …
Category: Web

How to Object.freeze wp_localize_script

I have a localize script that have sensitive information that i dont want other users change it from the console. is it possible to Object freeze my localized script? wp_localize_script('test-script', 'test_ajax', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('test-nonce'), 'action_thanks' => ACTION_THANKS, 'univ_short_name' => UNIV_SHORT_NAME, 'action_general' => ACTION_GENERAL, 'action_catalog' => ACTION_CATALOG, 'action_ebook' => ACTION_EBOOK, 'university_id' => UNIVERSITY_ID, // in js needs to be converted to bool 'is_sf' => IS_SF ));
Category: Web

how to send Ajax request in wordpress backend

On the fronted the wp_localize_script seems to be working as when I view the source I can see the nonce. wp_localize_script('scripts', 'myAjax', array( 'root_url' => get_site_url(), 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce('wp_rest') )); For example, when I try get a list of users when logged into the wordpress backend I get a 401 unauthorised error. When I view the source my nonce is not there, only on the frontend. $.ajax({ url: 'https://example.com/wp-json/wp/v2/users/', method: 'GET', beforeSend: (xhr) => { …
Category: Web

Nonces, AJAX, script variables & security in WordPress

Alright, so let's say you develop a website where you enqueue a js script on a page X of your frontend, using: wp_enqueue_script( 'script_handle', PATH_TO_SCRIPT, array(), '1.0.0', true ); Inside this script, you use a simple AJAX request. You then use the nonce feature of wordpress to have what is stated as a safer AJAX request. And that nonce is passed to the script via: wp_localize_script( 'script_handle', 'object_name', array( 'nonce' => wp_create_nonce('my-specific-action') ) ); This creates a global javascript object, …
Category: Web

Enqueue scripts all over but not in single.php

I need to insert this script in the footer on the home, in categories, in pages, in the tags in the search but NOT in single.php: function live_search() { wp_enqueue_script('live_search', get_bloginfo('stylesheet_directory') .'/assets/js/live.search.js', array('jquery'), '1.0.1', true ); wp_localize_script( 'live_search', 'MovieWordpressSearch', array( 'api' => moviewp_url_search(), 'nonce' => moviewp_create_nonce('moviewp-search-nonce'), 'area' => ".live-search", 'more' => "Show all", ) ); } add_action('wp_enqueue_scripts', 'live_search'); Can someone help me? Thanks.
Category: Web

How to add extra attributes to the script tag added via wp_localize_script()

So, wp_localize_script() are awesome to add custom data to a script. And these data gets added to the HTML like: <script id='woocommerce_some-js-extra' type="text/javascript"> var wc_some_params = {"key":"sdfsfsdfs","use_iframes":"1","images_dir":"https:\/\/dadadasdad.com\/wp-content\/plugins\/woocommerce-some-gateway\/assets\/images"}; </script> This is all good. But the problem is that if I want to add an extra attribute to the script tag and instead of showing it like this: <script id='woocommerce_some-js-extra' type="text/javascript"> if I want to show it like this: <script id='woocommerce_some-js-extra' data-cfasync="false" type="text/javascript"> This is where I am facing the problem. I …
Category: Web

How to intercept already localized scripts

If a plugin uses some script (prominent example: jQuery UI Datepicker), but you're not happy with how the script renders the output, then there're two possibilities: 1. Unregister the script > Add your own version So first you'd need to check the handle, then find the priority and the hook (wp_enqueue_scripts, login_enqueue_scripts, etc.) ... you know the drill. 2. Change the jQuery plugin parameters Normally - if the plugin isn't crap - it pushes through the parameters from PHP to …
Category: Web

Is there a better way to access transients using javascript

I've been searching around the web trying to find a better way to use WordPress transients with javascript. Currently I am using admin-Ajax to run a php function that retrieves the transient and returns it. This works fine but I'm curios to know if there is a more effective way of accessing that data without the overhead of using ajax and php. I know I could probably do this using wp_localize_script() but I'm not sure if that method is any …
Category: Web

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.