PRO: JCI-twig-extensions
When using the JCI PRO Plugin select the “JCI-twig 3.5.1
” Parser. This Parser has the standard twig 3.X syntax, documented at https://twig.symfony.com/doc/3.x/templates.html
The JCI PRO Plugin adds many additional twig-filters and functions. With these you can many nice and helpfuld things.
Some twig-filter for sorting, formatting, replacing….
Filter-Syntax is like this:{% set filteredValue = (JSONVALUE | FILTER) %}
sortbyjsonfield
Sort JSON by chars, numbers or datessortbyarray
sort an array accoring to the PHP-sorting-funkctions. Syntax: {{… | sortbyarray(SORTTYPE, SORTFLAG) }}. Valid values for SORTTYPE are the PHP-sortingfunctions “asort”, “arsort”, “rsort”, “ksort” and “krsort”. Default for SORTFLAG is SORT_REGULAR, see other valid flags here.dateformat
By “dateformat” you can set timezone and language / locale of time- and date-output. See example here.formatnumber(decimals, dec_point, thousands_sep)
formats numerical JSON-data. See example here.convert2html
convert JSON-data into HTMLconverthex2ascii
convert hex-data from JSON to asciiremovespecialcharsinurl
build URLs by lower strings, replacing blanks into dashes, converting “ä” into “ae” etc.stringshorter(length, suffix)
cut a string to length and put a suffix (e.g. “…”) at the end. This is useful for creating a Teasertext out of a long texthtmlspecialchars_decode
like the PHP-function “htmlspecialchars-decode”html_entity_decode(FLAGS="", ENCODING="")
like the PHP-function “html_entity_decode”: if the HTML-Tags in the JSON-data are encoded (e.g. < is <) use this to get real HTML. in case use with parameters like html_entity_decode(FLAG, ENCODING)base64encode
like the PHP-function “base64_encode”base64decode
like the PHP-function “base64_decode”htmlentities
like the PHP-function “htmlentities”urldecode
Decodes URL-encoded stringremovenonprintable
strip everything except basic printable ASCII characters by preg_replace( ‘/[^[:print:]]/’, replacement, input)stripslashes
Un-quotes a quoted string, see stripslashespreg_replace('/PATTERN/', 'REPLACEMENT')
like the PHP-function “preg_replace”preg_match_all('/PATTERN/', flags=0, offset=0)
like the PHP-function “preg_match_all”preg_quote(delimiter=NULL)
Quote regular expression characters
like the PHP-function “preg_match_all”md5
like the PHP-function “md5”dump
output JSONARRAY by PHP-syntax print_R(JSONARRAY, TRUE)- Usage of twig for JSON starting with “[{“: See twig and it’s _context
Advances Filter: 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” transforms the Shortcode-Strings to twig-arrays which can be merged into one twig-array:
json_decode(ASSOC=FALSE, DEPTH=512, OPTIONS=0)
this json_decode works like the PHP json_decodejson_decode_4twig(TRUE, DEPTH=512, OPTIONS=0))
is the same as json_decode but always ASSOC=TRUE. This means, that only arrays are in the created JSON-Tree, which is need for using it with twig.{{% set myArray = (jsonString |json_decode_4twig) %}
doshortcode
Execute the WordPress do_shortcode in a string:{% set jsonArr = (string_with _shortcode | doshortcode)%}
See example here.
Store a mediafile in the WordPress-medialibrary
wp_mediastore(SOURCE_OF_MEDIA, parentPageId="", mediatitle="", postslug= "", content="", excerpt="", publishdate="", $postStatusUsed="", authorid="", sourcetype="",
withpath=TRUE, removeqm=FALSE, generate_thumbnails=TRUE, loadContext="", addfileformatname="")
stores a mediafile in the WordPress Medialibrary.
see also here for examples and code
SOURCE_OF_MEDIA
URL or filename of the mediafileparentPageId
If set the uploaded images is attached to the WP-Page (Page, Post, CPT) with this PageIDmediatitle
Name of the imagepostslug
Slug /URL of the uploaded mediafilecontent
Longer text for the imageexcerpt
Short text for the imagepublishdate
Set the publish date of the uploaded media (if empty: now)postStatusUsed
publish, future, draft, pending, private
if emtpy: publishauthorid
ID of the WP-User to which the mediafile should be assigned (if empty: set user whos executing the request as author)sourcetype
If “sourcetype” is “file”:
is not a URL but a filename with a path. Then use that for loading the file: Check if file is existing on the server, extract the filename and the path.SOURCE_OF_MEDIA
withpath=TRUE
The name of the uploaded image is either with the complete path (TRUE) or only the mediafilename itself (FALSE)removeqm=FALSE
The name of the uploaded image is calculated out of
. IfSOURCE_OF_MEDIA
is an URL with an “?” the info right of the “?” is ignored (TRUE) or used (FALSE) for calculating the mediafilenameSOURCE_OF_MEDIA
generate_thumbnails=TRUE
If “generate_thumbnails” is set FALSE, no thumbnails are created.
This is good when you have to upload many images (many 1000…) as fast as possible . Creating thumbnails consumes a lot of time. You can do that later or on demand.loadContext=""
Must be valid JSON, needed if the http-request for the mediafile needs some extra info (e. g. authentication).
Example:{"http": {"method": "GET", "header": ["Accept-language: en\r\n Cookie: foo=bar\r\n"]}}
addfileformatname=""
The name of the uploaded mediafile sometimes needs a fileformat at the end. e.g. “.jpeg”
Get name of uploaded mediafile
wp_mediafilename(
, SOURCE_OF_MEDIA
withpath=TRUE, removeqm=FALSE, sourcetype="", addfileformatname="")
Calc out of
the name of the uploaded mediafile.SOURCE_OF_MEDIA
Get Mediafiles
wp_medialist(postid="", pattern="")
gives a list of all mediafiles in the WP-Medialibrary or only those with a special PostID or a search-pattern.
Delete a mediafile from the WordPress-medialibrary
You need the PostID of the Mediafile to be deleted. wp_medialist
gives such PostIDs. Then use wp_delete_custom_post
Set and get featured Image
wp_set_featured_image(postid, thumbnail_id)
Add thumbnail_id as featured image of postid.
wp_get_featured_image(postid='', size='post-thumbnail', attr='')
Get the featured image.
Save binary imagedata base64_encoded
base64encode_savefile(FILENAME)
Open the binary file “FILENAME” and save it base64_decoded as “FILENAME-b64”.
Return: “FILENAME-b64”
Generate Custom Posts, create and update Custom Post Fields and Taxonomies
You can create Custom Post Types with twig or Shortcodes:
wp_new_custom_post
Create a new custom post: 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
- excerpt: Short text 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, the id of the current user is set.
- debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
{% set newpageid = wp_new_custom_post(slug_post_type, title, name, content, excerpt, publishdate, postStatusUsed, authorid, debug_boolean) %}
wp_insert_custom_field_keyvalue
Insert Custom Field Values: Once you created a Custom Post (see above), you have the id the new created Post “newpageid”.- pageid: id of the Page, e. g. “newpageid”
- key: Slug of the Value Custom Post Field
- value: Value for the Custom Post Field
Example: Add images to the Woocommerce-Product-Imagegallery
For that upload Images withwp_mediastore
to the medialibrary. This gives you an array of Image-IDs.
With{% set setpig = wp_insert_custom_field_keyvalue(pageid, "_product_image_gallery", imgwoo) %}
you can set the CPF for the Imagegallery.
imgwoo must be a comma-separated list of the Imageids:{% set imgwoo = (idofuploadedimageArr | join(',') ) %}
- debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
The following code inserts a key-value-pair in a Custom Post:
{% set cpfid = wp_insert_custom_field_keyvalue(pageid, key, value, debug_boolean) %}
wp_get_custom_field_value
- pageid: id of the Page, e. g. “newpageid”
- key: Slug of the Custom Post Field
- debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
{% set cpf_value = wp_get_custom_field_value(pageid, key, debug_boolean) %}
wp_get_cp_by_cpf_keyvalue
Get all custom posts by Custom Post Field keys and values:- 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
{% set cpids = wp_get_cp_by_cpf_keyvalue(slug_post_type, key, value, debug_boolean) %}
wp_insert_taxonomy
Insert a taxonomy-value of a Taxonomy:- 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
{% set cleartax = wp_insert_taxonomy(pageid, taxonomySlug, taxonomyValue, debug) %}
wp_clear_taxonomy
Delete all taxonomy-entries of a Taxonomy:- taxonomySlug: Slug of the Taxonomy
{% set cleartax = wp_clear_taxonomy(taxonomySlug) %}
wp_get_taxonomy
Get all taxonomy-entries of a Page- pageid: id of the Page, e. g. “newpageid”
- taxonomySlug: Slug of the Taxonomy
- debug_boolean: if TRUE debuginfo is displayed, otherwise ignored
{% set taxonomyArray = wp_get_taxonomy(pageid, taxonomySlug, debug) %}
wp_set_post_categories(postid, post_categories, append = false)
Set categories for a post, just like the WP-function ‘wp_set_post_categories‘.
Return: JSON of term taxonomy IDs of affected categories or Errormessage.
From JCI-Version 3.7.3 on.
wp_update_custom_post(postid, titel="", name="", content="", excerpt="", publishdate="", postStatusUsed="", authorid="", parentPageId="", debug=FALSE)
Update the Page with postid.
Return: JSON with “status” and “msg”wp_delete_custom_post(postid, force_delete = FALSE, debug=FALSE)
Delete Post with postid: Execution of wp_delete_postwp_get_attachment_image_url(attachment_id, size = 'thumbnail', icon = FALSE)
Get the URL of an image attachment.
Get basic data from WordPress or load file
wp_get_page_properties
Get WordPress page properties: Optional is a debug_boolean flag (default FALSE) and a PageID (default empty, then use current page)
Return: Array, with node “requestdata” has HTTP_REFERER, REQUEST_URI, QUERY_STRING, REMOTE_ADDR, and other Information.
{% set pageprop = wp_get_page_properties(debug_boolean, pageid="")) %}
get_data_of_uploaded_file
Get data “$_FILES” of uploaded files (e. g. a uploaded images or file):
{% set fileinfos = get_data_of_uploaded_file(filename_given_at_upload) %}
get_file
Load file from server-directory:
{% set fileinfos = get_file(filename) %}
wp_get_files_in_dir
Get the list of files in an Diretory as Array.
Possible Errors:- “invalid dir”: Argument is not an String – or a Path to an not existing directory
- “no permission to read dir”: Directory existing, but WordPress has no rights to read it
- “scan of dir failed”: PHP-scandir gave no valid result, hence no list of files
{% set dirpath = "./" %} {% set list_of_files = wp_get_files_in_dir(dirpath) %}
wp_get_memory
Get the used memory in MB used by wordpress until this function executed. If argmunet is TRUE “memory_get_peak_usage” (Returns the peak of memory allocated by PHP) is used, otherwise “memory_get_usage“.
is set in both cases to true – to get the real size of memory allocated from system.real_usage
{% set mempeak = TRUE %} {% set usedmemory_in_mb = wp_get_memory(mempeak) %}
Create a WordPress-User out of JSON
jci_user_create(username, password, email, role)
- With the following twig-function you can create WordPress-Users out of the JSON-data:
- username, password: mandatory data, usually from JSON-data
- email: optional, default empty
- role: optional, valid rolenames like “author”, “administrator” etc. must be used
{% set createUserResult = jci_user_create(username, password, email, role) %}
RETURN:
JSON with “success” either TRUE or FALSE. “result” has either an Error-Description or info on the successfully created user
{% set username= "myusername1" %} {% set password= "mypassword" %} {% set createUserResult = jci_user_create(username, password, '', 'author') %} {{createUserResult | dump}}, res: {{createUserResult.result}}
more: see JCI-twig-extensions for programming a database or woocommerce.