Skip to content

Instantly share code, notes, and snippets.

@Log1x
Last active March 22, 2019 05:52
Show Gist options
  • Save Log1x/d0d4f5aa5c8f7b6241548e5bc6678b1c to your computer and use it in GitHub Desktop.
Save Log1x/d0d4f5aa5c8f7b6241548e5bc6678b1c to your computer and use it in GitHub Desktop.
Import to WordPress from JSON
{
"0":{
"slug":"lorem-ipsum",
"title":"Lorem Ipsum",
"publish_date":"2018-10-12T05:00:00.000Z",
"featured_image":"https://link.to/image.jpg",
"content":"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque blandit tempus feugiat. Nullam purus massa, ultricies vel erat ac, tempor condimentum lorem. Etiam malesuada egestas tincidunt.",
"page_title":"Welcome to Lorem Ipsum",
"description":"Nulla sit amet massa fringilla eros tempor tempus. Fusce auctor arcu sed ipsum eleifend, sit amet tincidunt ligula porta."
}
}
<?php
namespace App;
global $sage_error;
add_action('after_setup_theme', function () use ($sage_error) {
if (! file_exists($data = __DIR__.'/data.json')) {
return $sage_error("{$data} could not be found.");
}
$data = json_decode(file_get_contents($data));
return collect($data)
->filter()
->flatMap(function ($post) {
if (get_page_by_title($post->title, 'OBJECT', 'post') || empty($post->content)) {
return;
}
$post->id = wp_insert_post([
'post_title' => $post->title,
'post_name' => $post->slug,
'post_date' => $post->publish_date,
'post_content' => collect($post->content)->implode(''),
'post_author' => 1,
'post_status' => 'publish',
'meta_input' => [
'_yoast_wpseo_title' => $post->page_title,
'_yoast_wpseo_metadesc' => $post->description ?? null
]
], true);
if (! is_wp_error($post->id) && ! empty($post->featured_image)) {
collect(['media', 'file', 'image'])
->map(function ($file) {
require_once(ABSPATH."wp-admin/includes/{$file}.php");
});
if ($post->featured_image = media_sideload_image($post->featured_image, $post->id, $post->title, 'id')) {
set_post_thumbnail($post->id, $post->featured_image);
}
}
return;
});
}, 20);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment