Skip to content

Instantly share code, notes, and snippets.

@giorgioriccardi
Last active September 21, 2019 07:41
Show Gist options
  • Save giorgioriccardi/5b40fb09bbb85d76805afecde08e55d7 to your computer and use it in GitHub Desktop.
Save giorgioriccardi/5b40fb09bbb85d76805afecde08e55d7 to your computer and use it in GitHub Desktop.
WP scraper/importer via API call, a rough proof of concept. Do NOT use into production or live environments!
<?php
// allow direct access to the file via front-end
// http://twentyninteen.local/wp-content/themes/twentynineteen/wp-content-task-runner.php
$path = preg_replace('/wp-content.*$/', '', __DIR__);
require_once $path . 'wp-load.php';
// test that we get some content
// var_dump(get_post(1));
// A collection of all APIs available:
// https://github.com/public-apis/public-apis
// All the Star Wars data you've ever wanted:
// Planets, Spaceships, Vehicles, People, Films and Species
// https://swapi.co/api/
for ($i = 1; $i < 2; $i++) {
$response = wp_remote_retrieve_body(wp_remote_get("https://swapi.co/api/planets/?page=" . $i));
$planets = json_decode($response)->results;
foreach ($planets as $planet) {
$inserted_planet = wp_insert_post([
'post_title' => $planet->name,
'post_content' => $planet->terrain,
'post_status' => 'draft',
], true);
if (is_wp_error($inserted_planet)) {
echo $planet->name . ' could not be fetched </br>';
} else {
echo '<strong>' . $planet->name . ' was fetched successfully</strong> </br>';
}
}
}
// Side-Loading WordPress For One-Off Tasks: https://youtu.be/L4qsMxhw7bs?t=295
@giorgioriccardi
Copy link
Author

Add a collection of public APIs:
https://github.com/public-apis/public-apis

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment