twig: Generate, update or delete Custom Post Pages out of JSON

Challenge: Create Custom Post Pages out of JSON. Update the data and delete pages in case they’re not in the JSON any more.

Solution:

  1. Create a Custom Post Type with slug “cptevent_2022” (e. g. with a Plugin like CPT UI).
    Add Custom Post Fields “id” and “name” (e. g. with a Plugin like Advanced Custom Fields)
  2. Create a new JCI-Template:
    URL: https://api.json-content-importer.com/extra/json/crest.json
    Name: crescat
    twig-template:
{% set slugCPT = "cptevent_2022" %}
{# CPF: id and name #}
{% set idArr = []  %}
{% for item in _parent  %}
    {% if item.id %}
        {% set id= item.id %}
        {% set idArr = idArr | merge([id]) %}
        {% set name = item.name %}
        {% set listofcpp = wp_get_cp_by_cpf_keyvalue(slugCPT, "id", id) %}
        {% if (listofcpp | length)==0 %}
            {# create new page #}
            {% set slug = name %}
            {% set content = (item | json_encode) %}
            {% set newpageid = wp_new_custom_post(slugCPT, name, slug, content) %}
            {% set newcpf = wp_insert_custom_field_keyvalue(newpageid, "id", id) %}
            newpageid: {{newpageid}} (id: {{id}}, name: {{name}})<br>
        {% else %}
            {# modify existing page #}
            {% for k,v in listofcpp %}
                modify pageid {{v}}  (id: {{id}}, name: {{name}})<br>
                {% set outdate = (currenttimestamp|date("U")) %}
                {% set modf = wp_insert_custom_field_keyvalue(v, "name", outdate) %}
            {% endfor %}
        {% endif %}
    {% endif %}
{% endfor %}
{# delete pages not in the current JSON #}
{% set listofcpp = wp_get_cp_by_cpf_keyvalue(slugCPT) %}
{% for k,v in listofcpp %}
    {% set cpfvalArr = wp_get_custom_field_value(v, "id") %}
    {% set isInJSON = FALSE %}
    {% for cpfval in cpfvalArr %}
        {% if cpfval in idArr %}
            {# there is JSON-data for that page #}
            {% set isInJSON = TRUE %}
        {% endif %}
    {% endfor %}
    {% if not isInJSON %}
        delete pageid: {{v}}<br>
        {% set delcpt = wp_delete_custom_post(v, TRUE) %}
    {% endif %}
{% endfor %}

This twig-code loops through the JSON and creates (if needed) a new Custom Post Page (CPP). Or – if CPP is already there – updates the CPP.
Also it loops through the existing CPP: If there is a CPP which is not in the JSON when updating, this CPP is deleted.

Shortcode:

[[jsoncontentimporterpro nameoftemplate="crescat"]]