Search code examples
phpwordpresswpml

Call a specific page in Wordpress from PHP with WPML


I have a Wordpress template which works with Blocks. You map a page in a Block and then you add this block on your Home. However, one Block doesn't have a mapping option, so I did the following.

I opened the PHP file from this specific block and add a code to call a page with the ID.

<?php
$my_id = 1575;
$post_id_1575 = get_post($my_id);
$content = $post_id_1575->post_content;
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
echo $content;
?>

The page has an ID=1575. However, when I use WPML to duplicate the page and create it in another language, it creates a new page with a new ID. Is there any way to check the language on the PHP that is selected and then call another page id?

For example:

<?php

if (language == "en") {
    $my_id = 1575;
} else {
    $my_id = 1580;
}
$post_id_1575 = get_post($my_id);
    $content = $post_id_1575->post_content;
    $content = apply_filters('the_content', $content);
    $content = str_replace(']]>', ']]>', $content);
    echo $content;
?>

Solution

  • To get the currently selected language in WPML, use the following code:

    global $sitepress;
    $language = $sitepress->get_current_language();
    

    That will return a two letter language code like 'fr' for French or 'it' for Italian.

    However, I think what you're trying to do is find out the link to a particular post in a different language. If you just need to do this on case by case basis, Barry Kooij wrote a function to accomplish this.

    If what you want is to give users the option to switch the language they view a post in, you should consider using WPML's language switcher or creating a custom WPML language switcher.