Skip to content

Use Localize Script For WP REST API Requests

When developing a single page app with the WP REST API we often have different URLs where we pull data. Typically I’m developing locally with a .test domain and working with a separate demo site on my live server. On top of that since I’m releasing these apps as themes, eventually I’m using WordPress’ JavaScript translate feature to handle the final requests. So ultimately I have three different “locations” where I’m pulling data from while creating a new app.

Today it occurred to me that I can make use of the translate feature from the beginning and skip having different environments to set up. In my Vue apps, I’m using Axios to handle all API requests. To speed that up, I have an environment file that looks like this:

Now all I have to do is import this environment.js file and reference it for my requests like so:

Previously I had to swap the URL in environment.js to whichever site I was going to be working on at that time. Eventually I would swap it out to use a variable for the baseURL that WordPress could then “translate” to be the site URL. That way I don’t need my theme users to edit the app files to update the site URL. WordPress does it for us.

But since WordPress is just building on a native feature of JavaScript with its translation and I can do the same. So now my environment.js file looks like this:

and in my index.html file, the one I’m using when I develop the app, I’ve added this in:

right after the spot where the app files are injected. Now I don’t have to worry about forgetting to change the environment when I make new builds. Inside the WordPress theme, it automatically generates that variable definition for me so the URL will match the current site. I just add this to the wp_enqueue_scripts() function where I load the files for my app:

In this case “app” is the handle of the file where the translation will take place.

This may have occurred to everyone but me, but I’ve seen enough WP Single Page Apps on Github to realize lots of people don’t make use of translation to adjust the base site URL. While we can ask the end user to update this by hand and run a build, most WordPress users are not going to use an theme that they have to break out a command line tool to use.

Leave a Reply

%d bloggers like this: