Obtain the language of a Wordpress page using javascript

Is there a way to determine the language of a Wordpress page using Javascript?

I have discovered a method to detect Spanish:

if(window.location.href.indexOf("/es/") > -1) {

However, if the website does not use Permalink Settings with "Post name", the language preference will be indicated by ?lang=es in the URL.

Furthermore, can the lang preference for a Wordpress page be something like "en-uk"?

Answer №1

One way a reliable WordPress translation tool could work is by automatically updating the <html> tag with the appropriate lang parameter, like so - in the case of American English:

<html lang="en-US">
... website content
</html>

For that reason, I believe it would be much easier to implement this function:

function getLanguage() {
    return document.getElementsByTagName('html')[0].getAttribute('lang');
}

Answer №2

I may not be an expert in wordpress, but from my understanding, languages are typically indicated either after the domain name or as a URL parameter. The code snippet provided below is capable of handling both scenarios.

// Here are some sample URLs that have been tested with this function:
// url = 'domain.com/sdfsdf/dafsfd?lang=es';
// url = 'domain.com/sdfsdf/dafsfd?lang=es&sdfsf=dfsdf';
// url = 'domain.com/en-uk';
// url = 'domain.com/en-uk/';
// url = 'domain.com/en-uk?dfsdfsdf=dfsdf&sdfsfsdf=dfsdfs';

var url = window.location.href;
var lang = getLanguage(url);
console.log(lang);

function getLanguage(url) {
    // Check if language is set via URL parameter
    if (url.includes('?lang=')) {
        return url.split('?lang=')[1].split('&')[0];
    }
    // If language is set within the URL route
    else {
        return url.split('/')[1].split('?')[0];
    }

}

Answer №3

If you want to achieve this, simply use the following code:

let userLanguage = document.documentElement.lang;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Execute a Node.JS query using an HTML select dropdown

My goal is to customize queries to a mySQL database based on the user's selection from select options on my website. Here is the HTML code: <select id = "year"> <option value = "yr" selected>Choose a Year</option> <option id = " ...

Phonegap - Retaining text data in a checklist app beyond app shutdown

This is my first time developing an app with Phonegap. I am looking to create a checklist feature where users can input items into an input field. However, I am struggling with figuring out how to save these items so that they remain in the checklist even ...

Switch the monitored variable's value in VueJS

` ` I have a data variable that is of boolean type, and I have included this in a watch hook. When the value changes to true, I execute certain tasks within the watch function and everything works perfectly.` `watch: {` ` boolVar: func ...

Vue is removing a DOM node during the created lifecycle hook to set up a component

I am currently working on understanding the issue with this example that is not behaving as expected. My goal is to initialize my ContentView using the server-side rendered HTML in the DOM. I plan to check if init__main-content exists and then initialize t ...

Error: Attempting to access 'props' property of undefined when clicking on a button within a React application leads to a TypeError

I'm currently working on implementing two buttons that will enable navigation to different pages within my React app. However, I encountered an error when attempting to use the button labeled "home." TypeError: Cannot read properties of undefined (rea ...

Binding Data in Vue Multiselect

After extensive searching, I stumbled upon an amazing searchable select Vue component that has caught my eye: https://github.com/monterail/vue-multiselect. However, there seems to be a small issue when it comes to feeding it an array of objects as options ...

The integration of Zoom SDK with React and Node inevitably leads to encountering errors

I have been struggling to integrate zoomsdk into my react app and have followed all the steps mentioned here. The backend part is functioning properly, and I am receiving the signature response. However, when attempting to run the frontend portion, I encou ...

I must add and display a tab for permissions

I am currently using the material UI tab for my project. My goal is to display the tab only when the permission is set to true. I have successfully achieved this functionality, but the issue arises when the permission is false. It results in an error that ...

Tips for displaying an asp.net form using javascript functions

I am currently developing a login page in asp.net and have utilized a template from CodePen at http://codepen.io/andytran/pen/PwoQgO It is my understanding that an asp.net page can only have one form tag with runat="server". However, I need to incorporate ...

Utilizing Ajax to dynamically display the outcome of selecting a radio button

I am currently working on a script that aims to utilize Ajax in order to post the result of a radio button click. My progress so far includes: <label> <input type="radio" name="DisableAd" value="0" id="RadioGroup1_0" /> Radio </lab ...

Tips for placing <div .right> above <div .left> when the window is small, given that <div .right> is positioned to the right of <div .left> when the window is large

I've come across a similar layout before, but I'm struggling to replicate it myself. The idea is to have text aligned on the left side with an image floated to the right. Instead of the image appearing below the text when the window size is red ...

Updating elements within an array on the fly

In this scenario, let's consider two arrays: array A = [2, 5, 6] and array B = [1, 2, 3, 4, 5, 6, 7, 8]. The values of array B are initially hidden within boxes and become revealed when clicked. The goal is to replace certain values in array B with un ...

In the process of making a request with axios in an express server

Struggling with a simple call to an API using Axios with Express, and I can't figure out why it's always pending in the browser. Here is my route: var express = require("express"); var router = express.Router(); const controller = require("../. ...

What is preventing me from setting the maxwidth in Android WebView during onLayout?

I am attempting to customize the onLayout function of a WebView in order to limit the size of large images to fit within the screen size. Within my extended WebView, I have tried the following code: @Override protected void onLayout(boolean changed, i ...

What could be causing my CSS navigation toggle button to malfunction?

My attempt at creating a toggle button for tablets and phones seems to be failing. Despite the javascript class being triggered when I click the toggle button, it is not functioning as expected... https://i.stack.imgur.com/j5BN8.png https://i.stack.imgur. ...

Tips for updating text in a freshly opened window using JQuery or JavaScript

I have a function that is triggered by a button click to open a new window or tab, display an alert, and update text. Here is the code snippet: function nWin(p) { var setStyle = "<style rel='stylesheet'>\ .vTop {\ ...

Troubleshooting: Node.js Express Server GET Handler Failing to Function

Recently, I've been attempting to build a GET request handler in Express.js. Here's the snippet of code I've put together: // include necessary files and packages const express = require('./data.json'); var app = express(); var m ...

Discovering descendant div elements

I've been conducting some research, but I'm struggling to find a specific answer for this. Here is the HTML code snippet: <div class="collapsingHeader"> <div class="listItemWrapper"> <div class="itemWrapper"> ...

Check for input validation with jQuery when the element has a specific class

Utilizing the jQuery validation plugin for a checkout form on an ecommerce platform has proven to work excellently. However, I am in need of validating only those inputs that do not possess the class no-validate. Would it be possible to make use of the de ...

Unable to invoke a function in TypeScript from a Kendo template within the Kendo TreeList component

In my TypeScript file for class A, I am encountering an issue with the Kendo TreeList code. I am trying to call a function from the Kendo template. export class A{ drillDownDataSource: any; constructor() { this.GetStatutoryIncomeGrid ...