I have been tasked with creating geolocation pages that will all use the same exact template. The content writer is giving me all the "text" for the pages (which I am converting to json). I want to be able to loop over wp_insert_post() and the json data to create "x" amount of pages automatically without manually having to go in the editor for each page. I have been attempting this on my own with no real luck so far but here is the code I have:

Here is dummy json for my tests (wont work as a seperate file for some reason but will be getting it from AWS S3 bucket in the end result)

const people = [
    "id": 1,
    "first_name": "Darla",
    "last_name": "Garwill",
    "email": "dgarwill0@sogou.com",
    "gender": "Female"
    "id": 2,
    "first_name": "Mona",
    "last_name": "Roles",
    "email": "mroles1@guardian.co.uk",
    "gender": "Female"
    "id": 3,
    "first_name": "Cori",
    "last_name": "Danilowicz",
    "email": "cdanilowicz2@rakuten.co.jp",
    "gender": "Male"

This is included in my functions.php. (I want to be able to get all the data and structure it within the template. Kind of like passing props in react to the jsx.

function create_page_function() {
    // json I want to get the content from
    $json = file_get_contents($json_feed);
    $obj = json_decode($json, true);

    // foreach to loop over the json content
    foreach($obj['people'] as $page_array){

        // Save said content in variables
        $name= $page_array['first_name'];
        $email= $page_array['email'];

        $page = wp_insert_post(
            'post_title' => ucwords($name),
            'post_name' => strtolower(str_replace(' ', '-', trim($name))),
            'post_content' => $email,
            'post_author' => 1,
            'post_status' => 'draft',
            'post_type' => 'page',
            'comment_status' => 'closed',
            'page_template' => './templates/template.php'
        return $page;


Then I have a template set up like so called template.php (for testing right now):

 * Template Name: Test - Template
 * Template Post Type: page
 * @package WordPress
 * @subpackage Twenty_twenty_two
 * @since Twenty Twenty Two 1.0

<!DOCTYPE html>
<html <?php language_attributes(); ?>>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <h2>Name: <?php echo $name?></h2>
        <p>Email: <?php echo $email?></p>

Any help would be greatly appreciated!

Again to summarize. I want to loop over json data and create "x" amount of pages based on how many json objects there are and put the content in the template.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.