Last active
April 10, 2021 17:16
-
-
Save sirtimid/c8747dcd3bfba4f60693cb85b63819f3 to your computer and use it in GitHub Desktop.
Translate media automatically when using Polylang in Wordpress
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
if ( !function_exists( 'translate_all_media' ) ) { | |
function translate_all_media() { | |
global $polylang; | |
if(!$polylang) return; | |
// find languages | |
$langs = array(); | |
foreach (pll_languages_list() as $lang){ | |
if(pll_default_language() !== $lang){ | |
$langs[] = $lang; | |
} | |
} | |
// find media | |
$posts = get_posts(array( | |
'post_type' => 'attachment', | |
'posts_per_page' => -1, | |
'lang' => pll_default_language(), | |
)); | |
$int = 0; | |
foreach ($posts as $post) { | |
// itterate over all langs | |
foreach ($langs as $new_lang) { | |
// Bails if the translations already exists | |
if ( ! $polylang->model->post->get_translation( $post->ID, $new_lang ) ) { | |
$int++; | |
// creates the translation | |
$polylang->posts->create_media_translation( $post->ID, $new_lang ); | |
} | |
} | |
} | |
// notify admin | |
if($int > 0){ | |
echo '<div class="notice notice-success is-dismissible"><p>'; | |
echo 'Translated '.$int.' media'; | |
echo '</p></div>'; | |
} | |
} | |
add_action( 'admin_notices', 'translate_all_media' ); | |
} |
Excellent!
I wonder why the "if(pll_default_language() !== $lang)" con is needed when populate the $langs array beforehand...
I've noticed that loading an image from inside a post in DEFAULT language, it works (i.e.: the media library updates with the loaded attachment post fro all the languages available); but if you load an image from a post of an ALTERNATIVE language (not DEFAULT), the media library doesn't not automatically translate.
However, knowing that, it works like a charm!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks!