Using WordPress Base URL in JavaScript

Problem

In certain situations, there is a need to access the base URL of a WordPress site in JavaScript. However, once the JavaScript file is built, it becomes challenging to modify it. When WordPress is installed and mapped to the root of the domain, it is relatively easier to start the URL with /. However, if WordPress is located inside a folder, such as /demo, it is not possible to name it relatively.

Solution

To address this problem, we can leverage the wp_localize_script() function provided by WordPress. This function allows us to pass server-side data, such as the WordPress base URL, to our JavaScript code.

Here is an example of how to utilize wp_localize_script() to make the WordPress base URL available in your JavaScript:

function enqueue_scripts() {
    // Enqueue your JavaScript file
    wp_enqueue_script( 'your-script', get_template_directory_uri() . '/js/your-script.js', array(), '1.0', true );

    // Pass the WordPress base URL to your JavaScript file
    wp_localize_script( 'your-script', 'wpData', array(
        'baseUrl' => esc_url( home_url() ),
    ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

In the above code, get_template_directory_uri() returns the URL of the current theme’s directory, and home_url() returns the WordPress base URL. By using wp_localize_script(), we assign the WordPress base URL to the wpData.baseUrl variable in your JavaScript file.

Now, in your JavaScript file (your-script.js), you can access the WordPress base URL as follows:

console.log(wpData.baseUrl);

By utilizing wpData.baseUrl, you can construct URLs or perform other operations that require the WordPress base URL.

This solution allows you to dynamically include the WordPress base URL in your JavaScript code, making it adaptable to different installation scenarios.

Remember to replace 'your-script' with the appropriate handle used for your script in both the PHP and JavaScript code.

Using this approach, you can conveniently incorporate the WordPress base URL in your JavaScript, even when WordPress is installed in a subfolder.

Note: The wp_localize_script() function is specific to WordPress and may not be applicable in non-WordPress environments.