Twig-template engine (PRO plugin)

The free Version of the JSON Content Importer-Plugin is based on the proprietary “JCI-parser” with some great features. This is good and still available.

But: If you want to have full control of your JSON, build applications etc. you need a better parser. For this the PRO-plugin comes with the popular Twig3-engine (https://twig.symfony.com/doc/3.x/templates.html).


The usage is as following:
Step 1 is getting access to the JSON-data with the PRO-plugin.

Step 2: The following shortcode gives you (if there is access to JSON) all the JSON-data by the twig-code “{{_context | json_encode}}”:

[jsoncontentimporterpro debugmode=10 url=URL_FROM_API parser=twig3]all json:{{_context | json_encode}}[/jsoncontentimporterpro]

The better way is to use Twig via the PRO plugin-templates:.


Remarks: You might set and use the human readable name of the PRO-plugin-template like “nameofmytemplate” to have a Shortcode like this (instead of the id-number):

[jsoncontentimporterpro nameoftemplate=nameofmytemplate]

Twig-syntax:

Sometimes the devil is in the detail:


Twig has many powerful commands, but sometimes more is needed. Therefore in the PRO plugin several additional Twig-extensions are added:

Execute Shortcodes and create JSON out of a String

Especially if you want to merge several JSON-Feeds to one JSON-Feed “doshortcode” and “json_decode” are helpful: By “doshortcode” you can execute other JSONContentImporter-Shortcodes which give JSON and “json_decode_4twig” or “json_decode” tranforms the Shortcode-Strings to twig-arrays which can be merged into one twig-array:

Generate Custom Posts, create and update Custom Post Fields and Taxonomies

You can create Custom Posts with a Shortcode or with some Twig-Commands:

  • Create a new custom post:

    {% set newpageid = wp_create_new_custom_post(slug_post_type, title, name, content, publishdate, postStatusUsed, authorid, debug_boolean) %}

    This twig-function executes wp_insert_post

    • slug_post_type: Slug of the Custom Post Type, as defined when creating a Custom Post Type
    • title: Title of the created Page
    • name: Name of the created Page
    • content: E. g. HTML content for the created Page
    • publishdate: Set a date, the plugin tries to convert it into the needed format
    • postStatusUsed: Set the status like “publish”, “draft” etc. (all details see here)
    • authorid: WordPress-id of the user which should be the author of the Custom Post. If not set ther id of the current user is set.
    • debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
  • Insert Custom Field Values: Once you created a Custom Post (see above), you have the id the new created Post “newpageid”.
    The following code inserts a key-value-pair in a Custom Post:

    {% set cpfid = wp_insert_custom_field_keyvalue(pageid, key, value, debug_boolean) %}
    • pageid: id of the Page, e. g. “newpageid”
    • key: Slug of the Value Custom Post Field
    • value: Value for the Custom Post Field
    • debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
  • Get a Custom Field Value from a page:
    {% set cpf_value = wp_get_custom_field_value(pageid, key, debug_boolean) %}
    • pageid: id of the Page, e. g. “newpageid”
    • key: Slug of the Custom Post Field
    • debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
  • Get all custom posts by Custom Post Field keys and values:
    {% set cpids = wp_get_cp_by_cpf_keyvalue(slug_post_type, key, value, debug_boolean) %}
    • slug_post_type: Slug of the Custom Post Type, as defined when creating a Custom Post Type
    • key: Slug of the Custom Post Field
    • value: Value of the Custom Post Field
    • debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
  • Insert a taxonomy-value of a Taxonomy:
    {% set cleartax = wp_insert_taxonomy(pageid, taxonomySlug, taxonomyValue, debug) %}
    • pageid: id of the Page, e. g. “newpageid”
    • taxonomySlug: Slug of the Taxonomy
    • taxonomyValue: Value for the Taxonomy
    • debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
  • Delete all taxonomy-entries of a Taxonomy:
    {% set cleartax = wp_clear_taxonomy(taxonomySlug) %}
    • taxonomySlug: Slug of the Taxonomy

Get basic data from WordPress or load file

  • Get wordpress page properties:

    {% set pageprop = wp_get_page_properties(debug_boolean) %}
  • Get data “$_FILES” of uploaded files (e. g. a uploaded images or file):
    {% set fileinfos = get_data_of_uploaded_file(filename_given_at_upload) %}
  • Load file from server-directory:
    {% set fileinfos = get_file(filename) %}

Create a WordPress-User out of JSON

  • With the following twig-function you can create WordPress-Users out of the JSON-data:

    {% set createUserResult = jci_user_create(username, password, email, role) %}

    username, password: mandatory data, usually from JSON-data

    email: optional, default empty

    role: optional, valid rolenames like “author”, “administrator” etc. must be used

    RETURN: createUserResult: {{createUserResult.success}} either TRUE or FALSE. {{createUserResult.result}} has either an Error-Description or info on the successfully created user

    EXAMPLE:

    {% set username= "myusername1" %}
    {% set password= "mypassword" %}
    {% set createUserResult = jci_user_create(username, password, '', 'author') %}
    {{createUserResult | dump}}, res: {{createUserResult.result}}
    

Direct access to the (WordPress-)Database

  • Create a database-table: TAKE CARE!!
    To execute a command like “CREATE TABLE db_table_name(name-of-column1 datatype-column1, name-of-column2 datatype-column2,…)” you can use this twig-function:

    {% set dbresult = jci_db_create(db_table_name, json_for_db) %}

    json_for_db must be a JSON like {“name-of-column1″:”datatype-column1″,”name-of-column1″:”datatype-column2”,…}

    Yet jci_db_create is a simple create. E. g. you can’t create primary keys (no “CONSTRAINT [constraint_name] PRIMARY KEY [ USING BTREE | HASH ] (column1, column2, … column_n)” or using “ALTER”-Commands). Do that with tools like PHPMyAdmin.

    RETURN: JSON as twig-array, so by {% if dbresult.success %} you can check if the execution was successful

    {"success":false,"result":"Table 'newdb' already exists"} 

    or

    {"success":true,"result":true}  

    EXAMPLE:

    {% set tname = "newdb" %}
    {% set dbres = jci_db_create(tname, '{"no1":"int", "no2":"varchar(255)"}') %}
    <br>{{dbres| dump }}, res: {{dbres.result}}
    
  • Insert data into a database-table:
    To execute a command like “INSERT INTO db_table_name (‘key1’, ‘key2’,… ) VALUES (‘val1’, ‘val2’,…)” you can use this twig-function:

    {% set dbresult = jci_db_insert(db_table_name, json_for_db, is_wp_db) %}

    json_for_db must be a JSON like {“key1″:”val1″,”key2″:”val2”,…}

    is_wp_db: optional, default is 1. if set to any value than 1 the WordPress-Database Prefix is NOT added to get databases besides WordPress.

    RETURN: JSON as twig-array, so by {% if dbresult.success %} you can check if the execution was successful. dbresult{‘result’} has an Error-Description if success is FALSE.

    EXAMPLE:

    {% set tname = "newdb" %}
    {% set ti =("now"| date("U"))  %}
    {% set ra = random(50, 200) %}
    {% set datain = '{"no1": '~ti~', "no2": '~ra~'}'  %}
    datain: {{datain }}<br>
    {% set dbres = jci_db_insert(tname, datain, 'otherthan1') %}
    insert:<br>
    {{dbres | dump }}, res: {{dbres.result}}
    
  • Select data from a database-table:
    To execute a command like “SELECT db_fields FROM db_table_name WHERE db_where” you can use this twig-function:

    {% set dbresult = jci_db_select(db_fields, db_table_name, db_where, is_wp_db) %}

    db_where: optional, default empty

    is_wp_db: optional, default is 1. if set to any value than 1 the WordPress-Database Prefix is NOT added to get databases besides WordPress.

    RETURN: JSON as twig-array, dbresult{‘success’} either TRUE or FALSE. dbresult{‘result’} has an Error-Description if success is FALSE. dbresult{‘result’} has the result of the Database-select if success is TRUE

    EXAMPLE:

    {% set tname = "newdb" %}
    {% set dbres = jci_db_select("*", tname, '', 'whatever2') %}
    {% if dbres.success %}
    select:<br>
    {% for i in dbres.result %}
    {{i.no1}}-{{i.no2}}<br>
    {% endfor %}
    {% else %}
    error: {{dbres.result}}
    {% endif %}
    
  • Update data in a database-table:
    To execute a command like “UPDATE db_table_name SET key1=val1, key2=val2, … WHERE db_where” you can use this twig-function:

    {% set dbresult = jci_db_update(db_table_name, json_for_db, db_where, is_wp_db) %}

    json_for_db must be a JSON like {“key1″:”val1″,”key2″:”val2”,…}

    db_where: optional, default empty

    is_wp_db: optional, default is 1. if set to any value than 1 the WordPress-Database Prefix is NOT added to get databases besides WordPress.

    RETURN: JSON as twig-array, dbresult{‘success’} either TRUE or FALSE. dbresult{‘result’} has an Error-Description if success is FALSE.

    EXAMPLE:

    {% set tname = "newdb" %}
    {% set dbres = jci_db_update(tname, '{"no2":54}', "no2>0", 3) %}
    <br>up: {{dbres| dump }}, res: {{dbres.result}}<hr>
    
  • Delete data from a database-table: TAKE CARE!!
    To execute a command like “DELETE FROM db_table_name WHERE db_where” you can use this twig-function:

    {% set dbresult = jci_db_delete(db_table_name, db_where, is_wp_db) %}

    db_where: optional, default empty

    is_wp_db: optional, default is 1. if set to any value than 1 the WordPress-Database Prefix is NOT added to get databases besides WordPress.

    RETURN: JSON as twig-array, dbresult{‘success’} either TRUE or FALSE. dbresult{‘result’} has an Error-Description if success is FALSE.

    EXAMPLE:

    {% set tname = "newdb" %}
    {% set dbres = jci_db_delete(tname, "no2>60", 53) %}
    <br>del: {{dbres| dump }}, res: {{dbres.result}}<hr>
    

Use the Woocommerce-API

The Plugin Woocommerce is the a great software for runnung Online-Shops. You can use the JCI-Plugin to connect an API with Woocommerce.

  • Authentatication: Get key and secret
    See the Woocommerce-Settings, tab “Advanced”. There you find a “REST API” Link. There you can define who can use the Woocommerce-API how. So set up a key with permissions “read/write”. You get an “Consumer key” and a “Consumer secret”.
    Copy both to a textfile, you need them for accessing the API.
  • Show all products
    Create a new JCI-Temaplte with this twig-template for the JSON-display:

    <hr>woo-products:<br>
    <ul>
    {% for p in _context %}
    {% if p.id %}
    <li>{{p.id}}: {{p.name}}, sale_price: {{p.sale_price}}</li>
    {% endif %}
    {% endfor %}
    </ul>
    

    This URL (replace YOUR_DOMAIN):

    YOUR_DOMAIN/wp-json/wc/v3/products
    

    Curloptions (replace consumer_key, consumer_secret and YOUR_DOMAIN by real values):

    CURLOPT_HTTPHEADER={{ jci_woo_calc_auth('consumer_key', 'consumer_secret',  'YOUR_DOMAIN/wp-json/wc/v3/products' , 'GET') }}
    

    This JCI-Temaplte should show you all products in the Woocommerce at YOUR_DOMAIN

  • Add products
    For that you must create two new JCI-Temaplte:
    1st JCI-Template:
    twig-template:

    {{_context | json_encode }}
    

    Name of Template:

    dowoo
    

    Curloptions:

    ##param1##
    

    2nd JCI-Template:
    twig-template:

    {% set wurl = 'YOUR_DOMAIN/wp-json/wc/v3/products' %}
    {% set wmeth = 'POST' %}
    {% set customer_key= '.....' %}
    {% set customer_secret = '.....' %}
    {% set prod = '{"name": "new product",  "type": "simple", "description": "this is my new product",  "short_description": "short: this is my product in short"}' %}
    
    {% set wooauthstr = "CURLOPT_HTTPHEADER=Content-Type:application/json##" ~jci_woo_calc_auth(customer_key, customer_secret, wurl , wmeth )~ ';CURLOPT_POSTFIELDS='~prod  %}
    
    {% set jc = '[jsoncontentimporterpro  orderofshortcodeeval=10 httpstatuscodemustbe200=no nameoftemplate=dowoo url="'~wurl~'" method="'~wmeth~'" param1=\''~wooauthstr~'\']' %} 
    {% set z1 = (jc |doshortcode) %}
    
    {% set z = (z1 | json_decode(TRUE) ) %}
    product inserted
    

    URL:

    dummyrequest
    

Set and Get Cookies

When you load a WordPress-Page, maybe also a Cookies is sent from you to the Server. E. g. a Session-Cookie which tells the Server that you are logged in.
Esp. by evaluating a sent cookie you’re able identify who is requesting the page and what data should be displayed therefore.

  • In a JCI-Template you load JSON-data from an API. But you show only those parts of the data which a loggedin user has rights for. Those rights can be managed by Cookies.
    With a twig-function you can set and get cookie-data.

    See this Example:

    {% set setcookie = jci_setcookie('testname', 'testvalue') %}
    <hr>
    {% set getcookie = jci_getcookie('testname') %}
    getcookie: {{getcookie}}<hr>
    {% if getcookie %}
    cookie testname is set 
    {% endif %}
    show all cookies; {{ jci_getcookie() | json_encode }}
    

    jci_setcookie(name, value=””, expires=0, path=””, domain=””, secure=false, httponly=false) is used like the PHP-setcookie

    jci_getcookie(name) gives $_COOKIE[name]

    jci_getcookie() gives the complete $_COOKIE with all Cookies

forward to another Page: TAKE CARE!!

By sending a Location-Header you can force WordPress to jump to another page. This is very dangerous if you calc the target page dynamic, as you might forward to malicious pages!
So this should be used only if you know what you do!

It is helpful if you offer a form for inserting data, send this data to an API. Without forward a simple reload sends the data again and: If you want to display new and old data you hae to send an API-request again or process new and old data in the template.
With an forward you send the user to a page where a API-request is done only for displaying all data.

  • Syntax:

    {{jci_forward(“a_new_url”) }}