# 5. Dynamic data

Jikji inserts data with **expression bindings**: `j:text` for escaped text, `j:html` for trusted HTML, `j:attr:<name>` for an attribute, `j:if` for a condition, `j:each` for a loop. Expressions are PHP and call Jikji's helpers. In the editor they are set in the **Data** section of the right panel; by hand they are written as attributes ([Syntax reference](08-syntax.md)).

## 5.1 Context

| Document | `$post` | Also |
|---|---|---|
| Page or post | That page or post | — |
| Template or part | The request's post — the single post, the first post of a list, or `null` | `$query`, the main `WP_Query` |
| Inside a loop | Unchanged | The loop variable (`$item`, `$row`, `$term`…) |

Helpers take their context **explicitly** — `jikji_post('title', $post)` and, inside a loop, `jikji_post('title', $item)`. Every helper returns a value and never echoes. A missing field or meta is an empty value, not an error.

In the editor the **data picker** chooses the context (the current post or a loop variable in scope) and shows that context's schema in tabs — Post, Meta, Terms, ACF, Custom, and for templates Site and Archive. Children of a loop default to the innermost loop variable. Picking an HTML-kind source switches on *Output as HTML*. URL attributes (`href`, `src`, `action`, `poster`) only accept fields that yield a single URL; list fields are for loops. The canvas shows **sample values** evaluated by the server (escaped like the front end); a bound text block keeps its typed text as the canvas placeholder, shown as a label chip when no sample is available.

## 5.2 Post fields — `jikji_post( $field, $post, $arg = null )`

| Field | Kind | Note |
|---|---|---|
| `title` `excerpt` `slug` `author_name` `type` `status` `comment_count` | text | |
| `content` | html | The body with `the_content` filters (use `j:html`). Another Jikji document's body inside a loop is its raw `post_content` |
| `permalink` `author_url` | url | |
| `date` `modified` | date | Third argument: date format (site format by default) — `jikji_post('date', $post, 'Y.m.d')` |
| `thumbnail_url` | url | Third argument: image size (`large` by default) |
| `thumbnail` | html | The `<img>` tag (`post-thumbnail` size) |
| `thumbnail_id` `id` | id | |

## 5.3 Binding attributes

```html
<a id="{more}" href="#" j:attr:href="jikji_post('permalink', $post)" j:attr:title="jikji_post('title', $post)">Read more</a>
<img id="{img}" src="" alt="" j:attr:src="jikji_post('thumbnail_url', $post)" j:attr:alt="jikji_post('title', $post)">
```

- `href`, `src`, `action` and `poster` are passed through `esc_url()`, everything else through `esc_attr()`.
- A static attribute of the same name is the canvas placeholder; the bound value replaces it on the page.
- `null` or `false` drops the attribute entirely; `''` outputs an empty attribute (`alt=""`). That is how `aria-current="page"` or `open` are switched: `j:attr:aria-current="jikji_term('id', $term) === jikji_archive('term_id') ? 'page' : null"`.
- `id`, `class` and `on*` cannot be bound. The attribute name is a lowercase HTML attribute name.

## 5.4 Meta, terms, site, archive

| Helper | Returns |
|---|---|
| `jikji_meta( $key, $post )` | A scalar meta value as a string (array meta gives `''`). ACF-managed fields: use `jikji_field()` |
| `jikji_term_list( $taxonomy, $post, $sep = ', ' )` | Term names joined — `j:text="jikji_term_list('category', $post, ' · ')"` |
| `jikji_terms( $taxonomy, $post )` | `WP_Term[]` for a loop — `j:each="jikji_terms('post_tag', $post) as $term"` |
| `jikji_term( $field, $term )` | `id name slug link description count parent taxonomy` |
| `jikji_term_query( $json, $post = null )` | **All** terms of a taxonomy (`get_terms()` arguments as JSON, `taxonomy` required, `hide_empty` true by default) — filter bars. List tokens work (`"parent":"{archive:term_id}"`, `"include":"{post:field:topics}"`) |
| `jikji_site( $field )` | `name` `description` `url` (home) `logo_url` (custom logo or `''`) `icon_url` `language` |
| `jikji_archive( $field )` | Templates: `title` (text — "Category: News", a search title, "Page not found"), `title_html`, `description` (html), `type` (`home` `post_type` `category` `tag` `taxonomy` `author` `date` `search` `404` `singular`), `found`, `search_query`, `term_id` `term_slug` `taxonomy` (the term the request shows, else `''`), `post_type` |
| `jikji_main_query()` | The request's main query posts — list templates ([5.7](#57-the-main-query-and-pagination-templates)) |
| `jikji_pagination( $json )` | Main-query page links as HTML, `''` on a single page |
| `jikji_template_part( $slug )` | A part's HTML (normally written as `j:part`) |

The first post's terms (`jikji_terms('topic', $post)`) and the request's term (`jikji_archive('term_id')`) differ — "the topic being viewed" on an archive is the latter.

## 5.5 Loops

A loop goes on a container (Section, Div, List, a Link that holds blocks) as `j:each="<array expression> as $item"` (or `as $key => $item`). The **children** repeat; the container is output once, and not at all when the list is empty.

| Source | `j:each` | Item |
|---|---|---|
| Query | `jikji_query('<JSON>', $post) as $item` | `WP_Post` → `jikji_post(…, $item)` |
| Main query (templates) | `jikji_main_query() as $item` | `WP_Post` |
| A post's terms | `jikji_terms('category', $post) as $term` | `WP_Term` → `jikji_term(…, $term)` |
| All terms of a taxonomy | `jikji_term_query('{"taxonomy":"category"}') as $term` | `WP_Term` |
| ACF repeater | `jikji_field('features', $post) as $row` | A row → `jikji_row(…, $row)` |
| ACF relationship, multi post_object | `jikji_field('related', $post) as $item` | `WP_Post` |
| ACF gallery | `jikji_field('gallery', $post) as $img` | An image array → `jikji_row('url', $img)` |
| PHP array | `array('a', 'b') as $i => $label` | Anything (shown as Custom in the editor) |

Rules and behaviour:

- `j:if` on the same element is evaluated **outside** the loop; `j:attr` on the loop element too. The loop variable is for the children.
- Default variable names: Query `$item`, terms `$term`, repeater `$row` (a number is appended when the name is taken in scope). `$post`, `$this`, `$GLOBALS` and `$__jk_…` are refused.
- **IDs inside a loop get a suffix on the page** — `jk-card--1`, `jk-card--2`, nested `jk-card--1-2` (outer-inner). References within the same item follow (`for`, `aria-labelledby`, `aria-describedby`, `aria-controls`, `href="#…"`), so a FAQ button's `aria-controls` points at its own answer. A reference from outside the loop to an ID inside it gets a save warning — move it inside the item. The ID's style applies to every copy (`:is(#id,[id^="id--"])`). Front-end JavaScript should find looped elements by class or `data-*`, not by ID.
- Nested loops pass the outer variable as the inner context (`j:each="jikji_terms('category', $item) as $cat"`); use different names per level.
- The canvas shows the first item once and a "↻ $item · N items" badge. Samples are requested in batches of 200; items the server skipped are retried, then *Refresh samples* asks again.

## 5.6 Queries — `jikji_query( $json, $post )`

The argument is **`WP_Query` arguments as JSON** (in an attribute, `"` becomes `&quot;`).

| Rule | |
|---|---|
| Defaults | `post_status=publish`, `no_found_rows=true`, `ignore_sticky_posts=true`; `fields` is ignored; without `posts_per_page` the site's reading setting applies |
| Value tokens | `{post:ID}` `{post:post_type}` `{post:post_author}` `{post:post_parent}` inside string values are replaced from the context post |
| List tokens | `{post:terms:<taxonomy>}` (the context post's term IDs), `{post:field:<name>}` (an ACF/SCF field — posts, terms and attachments as IDs), `{archive:term_id}` `{archive:taxonomy}` `{archive:post_type}` (what the request shows). A value that is exactly a token becomes the list itself; inside a longer string the IDs are joined with commas |
| Empty list | An empty list token (no terms, empty field, not a term archive) yields **no results** rather than a wider query |
| Invalid JSON | An empty list: the container is not output. Check with `wp jikji eval` |
| Pagination | None (the main query has it). The same arguments in one request are queried once |

Frequent arguments:

| Goal | JSON |
|---|---|
| Latest 3 posts | `{"post_type":"post","posts_per_page":3}` |
| Other posts of the same type | `{"post_type":"{post:post_type}","post__not_in":["{post:ID}"],"posts_per_page":4}` |
| Child pages | `{"post_type":"page","post_parent":"{post:ID}","orderby":"menu_order","order":"ASC","posts_per_page":-1}` |
| By category slug | `{"post_type":"post","category_name":"news","posts_per_page":5}` |
| Taxonomy query | `{"post_type":"product","tax_query":[{"taxonomy":"product_cat","field":"slug","terms":["shoes"]}]}` |
| Ordered by a meta value | `{"post_type":"event","meta_key":"event_date","orderby":"meta_value","order":"ASC"}` |
| Same author | `{"post_type":"post","author":"{post:post_author}","post__not_in":["{post:ID}"]}` |
| 3 cases sharing a topic | `{"post_type":"case","tax_query":[{"taxonomy":"topic","terms":"{post:terms:topic}"}],"post__not_in":["{post:ID}"],"posts_per_page":3}` (add `"operator":"AND"` for *all* topics) |
| Another type, same topic | `{"post_type":"video","tax_query":[{"taxonomy":"topic","terms":"{post:terms:topic}"}],"posts_per_page":4}` |
| Topics chosen in a hub page's field | `{"post_type":"case","tax_query":[{"taxonomy":"topic","terms":"{post:field:hub_topics}"}],"posts_per_page":6}` |
| Posts of the archive term being viewed | `{"post_type":"{archive:post_type}","tax_query":[{"taxonomy":"{archive:taxonomy}","terms":"{archive:term_id}"}]}` |

The editor's Query presets include *Latest posts*, *Same type as this post*, *Children of this post*, *Same categories as this post* and *Posts of this archive term*.

A card list:

```html
<div id="{latest}" class="cards" j:each="jikji_query('{&quot;post_type&quot;:&quot;post&quot;,&quot;posts_per_page&quot;:3}', $post) as $item">
  <article id="{card}" class="card">
    <img id="{card_img}" src="" alt="" j:if="jikji_post('thumbnail_url', $item)" j:attr:src="jikji_post('thumbnail_url', $item, 'medium')" j:attr:alt="jikji_post('title', $item)">
    <h3 id="{card_title}"><a id="{card_link}" href="#" j:attr:href="jikji_post('permalink', $item)" j:text="jikji_post('title', $item)">Post title</a></h3>
    <p id="{card_meta}" j:text="jikji_post('date', $item, 'Y.m.d') . ' · ' . jikji_term_list('category', $item)">date · category</p>
    <p id="{card_excerpt}" j:text="jikji_post('excerpt', $item)">Excerpt</p>
  </article>
</div>
```

A term filter bar with the current term marked:

```html
<nav id="{chips}" class="chips" aria-label="Topics" j:each="jikji_term_query('{&quot;taxonomy&quot;:&quot;topic&quot;}') as $term">
  <a id="{chip}" class="chip" href="#" j:attr:href="jikji_term('link', $term)"
     j:attr:aria-current="jikji_term('id', $term) === jikji_archive('term_id') ? 'page' : null"
     j:text="jikji_term('name', $term)">Topic</a>
</nav>
```

## 5.7 The main query and pagination (templates)

Lists that the URL decides — archives, search, the posts page, and lists a site plugin builds with rewrites and `pre_get_posts` — use **`jikji_main_query()`**: pagination, 404 and `found` come with it. Secondary lists inside a page (related posts, latest three) use `jikji_query()`, which has no pagination. The URL rules and query policy belong to the site; Jikji renders.

```html
<main id="{main}">
  <h1 id="{archive_title}" j:text="jikji_archive('title')">Archive</h1>
  <div id="{archive_desc}" j:html="jikji_archive('description')"></div>
  <div id="{posts}" j:each="jikji_main_query() as $item">
    <article id="{post_card}">
      <h2 id="{post_title}"><a id="{post_link}" href="#" j:attr:href="jikji_post('permalink', $item)" j:text="jikji_post('title', $item)">Post</a></h2>
      <p id="{post_excerpt}" j:text="jikji_post('excerpt', $item)">Excerpt</p>
    </article>
  </div>
  <p id="{empty}" j:if="! jikji_main_query()">Nothing here yet.</p>
  <nav id="{pagination}" j:html="jikji_pagination('{&quot;prev_text&quot;:&quot;Previous&quot;,&quot;next_text&quot;:&quot;Next&quot;,&quot;mid_size&quot;:1}')"></nav>
</main>
```

`jikji_pagination()` arguments: `prev_text` `next_text` `mid_size` `end_size` as in `paginate_links()`; `before_page_number` `after_page_number` (HTML around every number); `current_before` (HTML before the **current** number only, e.g. `<span class="sr-only">Current page, </span>`); `type` `plain` (default) or `list` (`<ul class="page-numbers">`). HTML arguments pass through `wp_kses_post`; inside an attribute, HTML quotes in the JSON are written `\&quot;`. A page number out of range is a WordPress 404 (the 404 template renders).

## 5.8 ACF and Secure Custom Fields

`jikji_field( $name, $post, $as = null )` reads a field; ACF and SCF are handled alike. Values are normalized from the **field definition and the raw value**, so the field's "Return Format" setting does not matter; the third argument picks the shape:

| ACF type | `null` (default) | `'url'` | `'id'` | `'text'` |
|---|---|---|---|---|
| text, textarea, number, email, url, oembed, date/time | The string | same | same | same |
| image, file | Attachment array (`url` `alt` `title` `sizes`…) | URL | Attachment ID | Title / file name |
| link | `{url, title, target}` | `url` | — | `title` |
| post_object (single) | `WP_Post` | Permalink | ID | Title |
| relationship, post_object (multiple) | `WP_Post[]` (loop) | — | — | Titles joined with `, ` |
| taxonomy — single (`select`, `radio`) | `WP_Term` | Term link | Term ID | Name |
| taxonomy — multiple (`checkbox`, `multi_select`) | `WP_Term[]` (loop) | — | — | Names joined with `, ` |
| wysiwyg | HTML (`j:html`) | — | — | Text without tags |
| true_false | `true`/`false` (`j:if`) | — | — | `'1'` / `''` |
| select, checkbox, radio, button_group | Value (may be an array) | — | — | Label |
| repeater | Rows (loop, below) | — | — | Row count |
| gallery | Image arrays (loop) | — | — | Count |
| group | One row (read with `jikji_row()`; its fields are also readable as `<group>_<field>`) | `''` | `''` | `''` |
| flexible_content, clone, block | Raw value (not supported yet) | — | — | — |

`—` is `''`. An empty image, link or post_object is `null` without `$as` and `''` with it. Without ACF/SCF, `jikji_field()` is `null` — empty output, no error. A multiple-selection taxonomy field gives `''` for `'url'` and `'id'` even when it has values: loop over it instead (`j:each="jikji_field('topics', $post) as $term"`) and read `jikji_term('id', $term)` / `jikji_term('link', $term)`.

```html
<section id="{hero}">
  <p id="{badge}" j:if="jikji_field('show_badge', $post)">New</p>
  <h1 id="{title}" j:text="jikji_post('title', $post)">Title</h1>
  <p id="{subtitle}" j:text="jikji_field('subtitle', $post)">Subtitle</p>
  <img id="{hero_img}" src="" alt="" j:if="jikji_field('hero_image', $post, 'id')" j:attr:src="jikji_field('hero_image', $post, 'url')" j:attr:alt="jikji_row('alt', jikji_field('hero_image', $post))">
  <div id="{body}" j:html="jikji_field('body', $post)"></div>
  <a id="{cta}" href="#" j:attr:href="jikji_field('cta', $post, 'url')" j:attr:target="jikji_row('target', jikji_field('cta', $post))" j:text="jikji_field('cta', $post, 'text')">Call to action</a>
</section>
```

**Rows and groups — `jikji_row( $sub, $row, $as = null )`.** Each repeater row and each group is read with `jikji_row()`; sub-fields are normalized by the same table. Nested repeaters open another loop on the row (`j:each="jikji_row('children', $row) as $child"`). A group can be read as one row or, equivalently, by the stored name `<group>_<field>` — the editor's picker shows "Hero › Title" and inserts the second form. `jikji_row()` also extracts one key from any array (an image's `alt`, a link's `target`).

```html
<div id="{features}" j:each="jikji_field('features', $post) as $row">
  <article id="{feature}" class="feature">
    <h3 id="{f_title}" j:text="jikji_row('title', $row)">Feature</h3>
    <img id="{f_icon}" src="" alt="" j:if="jikji_row('icon', $row, 'id')" j:attr:src="jikji_row('icon', $row, 'url')">
    <p id="{f_text}" j:text="jikji_row('text', $row)">Text</p>
  </article>
</div>
<p id="{note}" j:text="jikji_row('note', jikji_field('hero', $post))">Note</p>
<h2 id="{hero_title}" j:text="jikji_field('hero_title', $post)">Title</h2>
```

**When a field is empty.** Decide what to show with the right test:

| Value | `jikji_field(…)` | Condition |
|---|---|---|
| number `0` | `"0"` | `j:if="'' !== (string) jikji_field('amount', $post)"` — shows 0 |
| empty text / number | `""` | same — hidden |
| never saved (new post, a field inside a group) | `null` | same — hidden (`!== ''` alone would let `null` through) |
| no image / file | `null` (`''` with `'url'`/`'id'`) | `j:if="jikji_field('photo', $post, 'id')"` |
| no relationship / repeater / gallery | `[]` | `j:each` hides the container; hide a heading with the same expression in `j:if` |
| true_false | `true`/`false` | `j:if="jikji_field('featured', $post)"` |

For example `<p j:if="'' !== (string) jikji_field('result_amount', $post)" j:text="number_format((int) jikji_field('result_amount', $post)) . ' USD'">0 USD</p>` shows a zero and hides an unfilled field.

## 5.9 Interaction (JavaScript)

- Put behaviour in the **theme** (or a site plugin) and enqueue it; the Jikji document provides the `class` and `data-*` hooks it needs — `j:attr:data-player="jikji_field('youtube_id', $post)"`.
- Looped elements have suffixed IDs, so scripts select by class or `data-*`.
- A `<script>` written in a document is output as-is on the front end, but it does not run on the canvas and scatters code across documents; the theme is the better place. Build players' `<iframe>`s on click.
- Test on the front end (Preview for drafts), not on the canvas.

## 5.10 Checking expressions before publishing

`wp jikji eval` (= `POST /render/data`) evaluates an expression in the document's context — for a template, inside its sample query — and returns the display value, so typos and empty fields are caught before anything goes live.

```bash
$WP jikji eval "$PAGE" "jikji_field('subtitle', \$post)"
$WP jikji eval "$PAGE" "jikji_field('features', \$post)" --mode=each          # "3 item(s) (row)"
$WP jikji eval "$PAGE" 'jikji_row("title", $row)' --scope='["jikji_field(\"features\", $post) as $row"]'
cat > checks.json <<'JSON'
[
  {"key": "subtitle", "expr": "jikji_field('subtitle', $post)", "mode": "text"},
  {"key": "has_badge", "expr": "jikji_field('show_badge', $post)", "mode": "if"},
  {"key": "features", "expr": "jikji_field('features', $post)", "mode": "each"},
  {"key": "first_feature", "expr": "jikji_row('title', $row)", "mode": "text", "scope": [{"each": "jikji_field('features', $post) as $row"}]}
]
JSON
$WP jikji eval "$PAGE" --items=checks.json --format=json
```

- `mode`: `text`, `html`, `attr` (with `--attr=<name>`), `each`, `if`. `--scope` is **one JSON array** of the enclosing `j:each` values, outermost first; expressions inside a loop are evaluated with each loop's first item. Up to 200 items per request.
- Errors give `jikji_eval_errors`; items left unevaluated after the time budget (5 s per request, retried twice by the command) give `jikji_eval_incomplete` — `data.results` holds what was evaluated. Over REST, items marked `skipped: true` are sent again.
- Templates: change the sample to test other contexts — `wp jikji template sample <id> --vars='{"cat": 3}'`, `{"s": "a"}`, `{"error": "404"}`, `{"p": 12, "post_type": "post"}` ([Templates 6.6](06-templates.md#66-the-sample-query)).
