Building a Multi-Language WooCommerce Store with Vue.js

The global reach of the internet demands that businesses cater to a diverse audience. For online stores, this means offering your website in multiple languages. This blog will guide you through the process of building a multi-language WooCommerce store powered by Vue.js. We’ll cover everything from setting up the WooCommerce backend to implementing language switching and product translation in your Vue.js frontend.

Understanding the Approach

Our solution will involve a two-pronged approach:

  1. WooCommerce Backend: We’ll use WooCommerce’s built-in translation features to manage product titles, descriptions, and other content. This allows us to maintain a single product database with multiple language versions.
  2. Vue.js Frontend: We’ll leverage the power of Vue.js to dynamically load and display the correct language content based on user preference. This includes using Vuex for state management, Vue Router for navigation, and a library like vue-i18n for translation.

Setting up the WooCommerce Backend

1. Install WooCommerce and Polylang:

  • Install WooCommerce from the WordPress plugin repository.
  • Install the Polylang plugin from the WordPress plugin repository. This plugin provides the core functionality for managing multilingual content in WordPress.

2. Configure Polylang:

  • Navigate to the Polylang settings page (Settings > Languages).
  • Configure your desired languages, including the default language and language codes.
  • Define how you want to handle language switching (URL structure, language switcher widget, etc.).

3. Translate Your WooCommerce Content:

  • Go to the product edit page for each product.
  • Use the Polylang interface to add translations for the product title, description, short description, and any other relevant fields.
  • Repeat this process for all your products, categories, and other content.

Building the Vue.js Frontend

1. Create a Vue.js Project:

Use the Vue CLI to create a new Vue.js project:

vue create woocommerce-vue-multi-language

2. Install Dependencies:

npm install axios vue-i18n vue-router vuex
  • axios: For making requests to your WooCommerce API.
  • vue-i18n: For handling translations.
  • vue-router: For routing between different pages in your Vue.js application.
  • vuex: For managing application state.

3. Setting Up Vuex Store:

Create a store/index.js file and define your store:

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    currentLanguage: 'en', // Set your default language
    products: [],
    loading: false,
    error: null
  },
  mutations: {
    SET_LANGUAGE(state, language) {
      state.currentLanguage = language;
    },
    SET_PRODUCTS(state, products) {
      state.products = products;
    },
    SET_LOADING(state, loading) {
      state.loading = loading;
    },
    SET_ERROR(state, error) {
      state.error = error;
    }
  },
  actions: {
    async fetchProducts({ commit, state }) {
      commit('SET_LOADING', true);
      try {
        const response = await axios.get(`${state.apiUrl}/wp-json/wc/v3/products?per_page=100`, {
          headers: {
            'Authorization': `Basic ${state.auth}`
          }
        });
        commit('SET_PRODUCTS', response.data);
        commit('SET_LOADING', false);
      } catch (error) {
        commit('SET_ERROR', error);
        commit('SET_LOADING', false);
      }
    }
  },
  getters: {
    getProducts: state => state.products,
    getCurrentLanguage: state => state.currentLanguage
  }
})

This sets up a Vuex store to manage your application state, including the current language, product data, loading state, and any potential errors.

4. Setting Up Vue Router:

Create a router/index.js file and define your routes:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  }
  // Add other routes here as needed
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

This sets up Vue Router to handle navigation between different pages in your application. You’ll need to create your Home.vue component and any other view components as needed.

5. Implementing Language Switching:

Create a components/LanguageSwitcher.vue component to allow users to change languages:

<template>
  <div>
    <select v-model="selectedLanguage" @change="changeLanguage">
      <option value="en">English</option>
      <option value="fr">French</option>
      <!-- Add more language options as needed -->
    </select>
  </div>
</template>

<script>
export default {
  data() {
    return {
      selectedLanguage: this.$store.getters.getCurrentLanguage
    };
  },
  methods: {
    changeLanguage() {
      this.$store.commit('SET_LANGUAGE', this.selectedLanguage);
      // Potentially reload products or perform other actions
    }
  }
}
</script>

This component provides a dropdown menu for users to select their preferred language. When a language is selected, it updates the currentLanguage in the Vuex store.

6. Setting Up Vue i18n:

Create a i18n/index.js file and configure your translation messages:

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

const messages = {
  en: {
    // English translation messages
    hello: 'Hello',
    productTitle: 'Product Title'
  },
  fr: {
    // French translation messages
    hello: 'Bonjour',
    productTitle: 'Titre du produit'
  }
  // Add more language translations as needed
}

const i18n = new VueI18n({
  locale: 'en', // Set your default language
  messages
})

export default i18n

This sets up Vue i18n and defines translation messages for each language. You’ll need to replace the placeholder messages with your actual translations.

7. Integrating i18n and Language Switching:

In your main.js, import and configure Vue Router, Vuex, and Vue i18n:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import i18n from './i18n'

Vue.config.productionTip = false

new Vue({
  router,
  store,
  i18n,
  render: h => h(App)
}).$mount('#app')

This sets up your application with all the necessary components and libraries.

8. Displaying Localized Content:

In your Vue components, use the $t helper from Vue i18n to display localized text:

<template>
  <div>
    <h1>{{ $t('hello') }}</h1>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$store.dispatch('fetchProducts');
  }
}
</script>

This example displays the localized greeting message based on the current language.

9. Fetching Translated Product Data:

In your store/index.js, when fetching product data from the WooCommerce API, you need to specify the language context in your API requests.

import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    currentLanguage: 'en', // Set your default language
    products: [],
    loading: false,
    error: null
  },
  mutations: {
    SET_LANGUAGE(state, language) {
      state.currentLanguage = language;
    },
    SET_PRODUCTS(state, products) {
      state.products = products;
    },
    SET_LOADING(state, loading) {
      state.loading = loading;
    },
    SET_ERROR(state, error) {
      state.error = error;
    }
  },
  actions: {
    async fetchProducts({ commit, state }) {
      commit('SET_LOADING', true);
      try {
        const response = await axios.get(`${state.apiUrl}/wp-json/wc/v3/products?per_page=100&lang=${state.currentLanguage}`, {
          headers: {
            'Authorization': `Basic ${state.auth}`
          }
        });
        commit('SET_PRODUCTS', response.data);
        commit('SET_LOADING', false);
      } catch (error) {
        commit('SET_ERROR', error);
        commit('SET_LOADING', false);
      }
    }
  },
  getters: {
    getProducts: state => state.products,
    getCurrentLanguage: state => state.currentLanguage
  }
})

This snippet modifies the fetchProducts action to include the lang query parameter in the request, ensuring you retrieve data in the correct language.

10. Displaying Localized Product Data:

In your product display components, use the $t helper to display translated product titles, descriptions, etc.:

<template>
  <div v-for="product in $store.getters.getProducts" :key="product.id">
    <h2>{{ $t('productTitle') }}: {{ product.name }}</h2>
    <p>{{ $t('productDescription') }}: {{ product.description }}</p>
  </div>
</template>

<script>
export default {
  mounted() {
    this.$store.dispatch('fetchProducts');
  }
}
</script>

This example iterates over the products fetched from your WooCommerce API and displays the localized name and description for each product.

Additional Considerations

  • URL Structure: Depending on your Polylang configuration, you may need to adjust your Vue Router routes to handle different language URLs (e.g., /en/products vs /fr/products).
  • Static Content: For any static content (e.g., navigation menus, page titles), you’ll need to create separate files with translations.
  • SEO: Ensure your language variations are properly implemented for SEO purposes (e.g., using hreflang tags).
  • Testing: Thoroughly test your website across multiple browsers and devices to ensure the multi-language functionality works as expected.
  • Performance: Optimize your application for performance by using techniques like lazy loading for images and code splitting for your JavaScript bundles.

Conclusion

Building a multi-language WooCommerce store with Vue.js allows you to cater to a global audience and expand your reach. By combining the power of WooCommerce’s translation capabilities with the dynamic nature of Vue.js, you can create a seamless and user-friendly multilingual experience for your customers.

This guide has provided a comprehensive framework for getting started. Remember to adapt and expand these techniques based on your specific needs and website structure. With dedication and a good understanding of the underlying principles, you can effectively build a multilingual WooCommerce store that empowers your business to thrive globally.

Leave a Reply

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

Trending