/blog/snippets/

Polylang Snippet: Automatically get id of translated page

I'm currently working on a multi-language Wordpress site project and while I'm trying to build everything without having to rely on specific page id's, it happens from time to time.

I'm using Polylang to achieve the multi-lang capability and this plugin is great. Thanks for the recommendation goes out to Nils. Let's say our default language is german and you need the title of a specific page and this page has the id of 52. This is how you would normally do it:

<?php echo get_the_title(52); ?>

But this will always return the german title of this page no matter the current language. That's because with Polylang a translation is just a new page which is internally linked to the other. This means the translation of page id 52 might actually be page id 106. So while I need the title of page id 52 in the default language I want to output the title of page id 106 when english is active. Luckily there's an easy way to do that with Polylang:

<?php echo get_the_title(pll_get_post(52)); ?>

This will recognise the link between page id 52 and 106, check the current language and use the right id. Happy end!

Martin Wolf

Hi, I’m Martin Wolf, a Freelance Frontend Web Developer from Germany.
I believe in hard work and sharing what I know.

Contact me

Interested in working with me? Fantastic! The best way to get in touch is by email (hello@martinwolf.org). I’m looking forward to hearing from you.