Skip to content

Instantly share code, notes, and snippets.

@isaactopo
Last active February 28, 2023 16:07
Show Gist options
  • Save isaactopo/bdb04266b05791e5c1a266b3c85d64af to your computer and use it in GitHub Desktop.
Save isaactopo/bdb04266b05791e5c1a266b3c85d64af to your computer and use it in GitHub Desktop.
Convert Markdown Posts to Kirby Blocks
<?php
// Converting Markdown posts to Kirby Blocks
// Useful for K2 to K3 content Migrations
// Or if you want to transform automatically your Markdown to Kirby Blocks
// Get posts
$posts = $page->children()->listed();
foreach ($posts as $post) {
// New Blocks Object
$newBlocks = new Kirby\Cms\Blocks();
// Convert the Markdown from the text field to HTML and to blocks
$blocks = $post->content()->get('text')->kt()->toBlocks();
foreach ($blocks as $block) {
// If The Block Type is not an image
if ($block->type() !== 'image') {
// This adds a Block type Text or List from the HTML to the $newBlocks Object
$newBlocks->add($block);
} else {
if(isset($imageName)) {
unset($imageName);
}
// We get the image basename ex: 1.png
$imageName[] = basename($block->content()->src());
// We create a new Image Block type.
// We do this to get the image as an image in the panel not an external URL
// with the 'location' => 'kirby'
$image = new \Kirby\Cms\Block([
"content" => [
'location' => 'kirby',
'image' => $imageName,
],
'type' => 'image',
]);
// we add the new image to the $newBlocks Object
$newBlocks->add($image);
}
}
// I do this to check if some posts are already a Kirby Block or not
if(!isJson($post->text()->value())){
$kirby->impersonate('kirby');
// Update the Page
$post->update([
// I'm transforming the Title to Lowercase Uppercase-first letter
'title' => ucfirst(mb_strtolower($post->title())),
'text' => json_encode($newBlocks->toArray()),
]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment