Skip to content

Instantly share code, notes, and snippets.

@paolosax
Forked from sirtimid/auto-polylang-media.php
Created April 10, 2021 14:06
Show Gist options
  • Save paolosax/ee0adb06950b01e6965bb48ab3c786c5 to your computer and use it in GitHub Desktop.
Save paolosax/ee0adb06950b01e6965bb48ab3c786c5 to your computer and use it in GitHub Desktop.
Translate media automatically when using Polylang in Wordpress
<?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' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment