The goal is to show on the page a single subheading chosen randomly from a list of subheadings. I thought I might set up this in the .txt file:
subheading:
-
Subheading One
-
Subheading Two
-
Subheading Three
and
<h2 >
<?= $page->subheading()->shuffle() ?>
</h2>
but that returns everything written in the .txt file so I suppose I’m taking a wrong approach.
How might I do this?
You cannot call shuffle() on a field object, you have to convert the value to a structure object first, then shuffle and get the first element:
<h2 >
<?= $page->subheading()->toStructure()->shuffle()->first() ?>
</h2>
Note that in your example above the parenthesis after subheading were missing as well.
Ha! I was still trying to get what I had actually written to render correctly in my inquiry and your answer appeared. I believe this is rendering more accurately to my attempt now. Not sure if that will change your answer or not but I’ll look up toStructure() in the docs.
Thanks so much!
Please always use three backticks before and after a code snippet to render it correctly, like this:

I used what we have above and got an “Invalid structure data” message. I took a look at the
$field->toStructure() docs
and emulated what was there with:
subheadings:
- subhead: Subheading Uno
- subhead: Subheading Due
- subhead: Subheading Tre
and, just to check, used the foreach() method from the docs, and those items are shown as a list exactly as in the docs.
Attempting to get the desired result of a single random shuffle() result, I have:
<h2> <?= $page->subheadings()->toStructure()->shuffle()->first() ?></h2>
which, interestingly, renders a single item on the page randomly- the position of the item in the array, so 0, 1, or 2.
I must be close but not sure what to try next. The examples in the docs that I have found are generally looping through the items and creating a list rather than what I am trying to do in this case.
ok, you either have to store your values like this
Subheadings:
- subheading 1
- subheading 2
- subheading 3
and then convert to an array with yaml()
<?php
$headings = $page->subheadings()->yaml();
shuffle($headings);
echo $headings[0] ?? '';
Or you store them like this:
Subheadings:
-
sub: subheading 1
-
sub: subheading 2
-
sub: subheading 3
And then fetch the first shuffled one like this:
$heading = $page->subheadings()->toStructure()->shuffle()->first();
if ($heading) {
echo $heading->sub();
}