Skip to content

Instantly share code, notes, and snippets.

@bvdputte
Forked from bezin/migrate-translations.php
Created September 13, 2024 14:28
Show Gist options
  • Select an option

  • Save bvdputte/60dbca2bead778e32fc65da7dae7bc1b to your computer and use it in GitHub Desktop.

Select an option

Save bvdputte/60dbca2bead778e32fc65da7dae7bc1b to your computer and use it in GitHub Desktop.
Change Kirby default language from English to German with existing content files
<?php declare(strict_types=1);
use Kirby\Cms\ModelWithContent;
/**
* This script assumes English is the default language and German is the translation.
* The goal is to switch this and make German the default language and English the translation.
*
* We want to update all pages, files metadata and the site.
*
* What the script CANNOT do: Update the folder names (English slugs in this case) in `content`
* to match the translated slug from the German content files.
*
* To migrate your content files, just create a template migrate-translations.php`, add an empty text file to
* `content/migrate-translations/migrate-translations.en.txt` and call this page from your browser.
*/
function migrateContent(ModelWithContent $model): void
{
// Read actual content in both languages for model
$enContent = $model->readContent('en');
$deContent = $model->readContent('de');
// If there is no German content, we assume it is German content in the English content file.
// We just copy over the „English“ content to the German content file and delete the English content file.
if (empty($deContent)) {
$model->writeContent($enContent, 'de');
$model->storage()->delete('published', 'en');
return;
}
$excessFields = array_diff(array_keys($enContent), array_keys($deContent));
// If there is a German translation already, we need to move over fields that are only stored in the default language, e.g.
// the UUID, slug (if not translated) or any field that has `translate: false` set in a blueprint.
foreach ($excessFields as $field) {
$deContent[$field] = $enContent[$field];
unset($enContent[$field]);
}
// Write new content in both languages
$model->writeContent($deContent, 'de');
$model->writeContent($enContent, 'en');
}
/** @var ModelWithContent $model */
foreach ([site(), ...site()->index()] as $model) {
if (in_array($model->template()->name(), ['migrate-translations', 'translation-status'])) {
continue;
}
echo '<pre>';
echo '# Migrating page ' . $model->title() . PHP_EOL;
migrateContent($model);
/** @var \Kirby\Cms\File $file */
foreach ($model->files() as $file) {
echo '* Migrating file' . $file->filename(). PHP_EOL;
migrateContent($file);
}
echo PHP_EOL . '====';
echo '</pre>';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment