Tuesday, July 7, 2015

Going Multilingual

Turning on multilingual plug-ins do more than just allow one to manage multiple versions of a single page / post; rather they deeply integrate with WordPress allows for multiple menus, categories, etc.  WordPress provides a number of options for multilingual WordPress: https://codex.wordpress.org/Multilingual_WordPress; all of which require a non-trivial investment in time to implement.

In the case where one wants to implement a limited multilingual experience, e.g., only a selection of pages / posts need to be provided in multiple languages, one can leverage the Advanced Custom Forms Pro plugin to create a lightweight solution.

The general idea is:

1. Create a new field group, e.g., multi, with the structure:
  • Field: repeat of type Repeater.
    • Field: language of type Select choices:
      • English
      • EspaƱol
      • Arabic
    • Field content of type Wysiwyg Editor.
2. Create a new custom page template, e.g, by copying page.php, to page_multi.php, and add the following PHP comment to the top.

page_multi.php
<?php /* Template Name: Multi Template */ ?>

3. Change the multi field group to apply if Page Template is equal to Multi Template.

4. Now we update page_multi.php to use the fields in the field group multi as follows:

page_multi.php
<?php /* Template Name: Multi Template */ ?>
<?php get_header(); ?>
<?php wp_nav_menu(array('theme_location' => 'header-menu')); ?>
<?php if (function_exists('yoast_breadcrumb')) {
   yoast_breadcrumb();
 }?>
<?php while (have_posts()) : the_post(); ?>
  <?php while (have_rows('repeat')) : the_row(); ?>
      <div id="<?php the_sub_field('language'); ?>" class="multi" style="display: none;">
        <?php the_sub_field('content'); ?>
      </div>
  <?php endwhile; ?>
  <ul>
    <?php while (have_rows('repeat')) : the_row(); ?>
        <li><a onclick="show('<?php the_sub_field('language'); ?>')"><?php the_sub_field('language'); ?></a></li>
    <?php endwhile; ?>
  </ul>
<?php endwhile; ?>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
<script>
  jQuery(document).ready(ready);
  function ready() {
    var language='English';
    var regex = /mylanguage=([^;]*)/;
    var match = document.cookie.match(regex);
    if (match) {
      language = match[1];
    } else {
      document.cookie='mylanguage=English; path=/';
    }
    show(language);
  }
  function show(language) {
    document.cookie='mylanguage=' + language + '; path=/';
    jQuery('.multi').hide();
    var content = jQuery('#' + language);
    if (content.length !== 0) {
      jQuery('#' + language).show();
    } else {
      jQuery('#English').show();
    }
  }
</script>

5. Finally, one can change a page's template to Multi Template to enable multiple languages for it.

No comments:

Post a Comment