jeudi 21 février 2019

Correct approach to build dynamic links between translated pages in Wordpress


I have a simple website built with Wordpress, https://ift.tt/2V9SZxs and I have the pages translated both in Italian and English.
As you can see on top of the screen (header.php) I set two anchor flags images. If you click on them you are redirected to the italian / english version of the page currently displayed.
The question is, how can I setup a simple, dynamic approach in the code to set the href="" to the translated version of the page? The pages are simple custom template files named servizi.php/servizi-eng.php, index.php/index-eng.php, about.php/about-eng.php etc. etc.
So far, I am trying to implement the approach with a series of if statements in the header but things are getting complicated. Here is what I mean.

<?php
$permalink = get_permalink();
?>
<div class="flag-container">
<!-- Italian Flag -->
    <a 
    href=           
    <?php 
    if (is_home()) {
        echo get_home_url();    
    }
    else {
        if (get_the_ID(90)) {
            echo get_home_url();
        }
        else {
            if (strpos($permalink, 'eng') == true) {
                echo str_replace('-eng', '', $permalink);
            }
        }
    }
    ?> 

    class="flags flag-icon"><img class="flag-icon" src="<?php echo get_bloginfo('stylesheet_directory') ?>/images/italy.png" alt=""></a>
    <!-- English Flag -->
    <a href=
    <?php 
    if (is_home()) {
        echo get_post_permalink(90);    
    }
    else {
        if (get_the_ID(90)) {
            echo get_permalink();
        }
        else {
            if (strpos($permalink, 'eng') == false) {
                echo removeB($permalink);
                echo "ciao";
                function removeB($a) {
                    $a = substr($a, 0, -1);
                    $a = $a."-eng";
                    return $a;
                }
            }
            if (strpos($permalink, 'eng') == true) {
                echo get_permalink();
            }
        }
    }
    ?> 
    class="flags flag-icon"><img class="flag-icon" src="<?php echo get_bloginfo('stylesheet_directory') ?>/images/united-kingdom.png" alt=""></a>
</div>

First, I set the conditional logic in case of the homepage. The post 90 is simply the english homepage (index-eng.php) file. Then, I set the logic for the other pages. As you can see I try to modify the permalink removing or adding the final -eng but it does not work. I am sure there is a better approach than this madness but so far I did not find it. Do you have any ideas?
Thanks in advance for all the help.

Aucun commentaire:

Enregistrer un commentaire