Fetch all values for custom field as loop

I’m looking for a way to get a list of all the values that exist for a certain custom field across all pages (or child pages of a certain page).

For instance if I have a custom field called Area I want to get a loop of every value that exists for that field. Ideally as a loop that I can add the value as a link to (I want to use them to filter the listings further using URL params, but don’t want to create every one manually).


Title: Page 1
Area: London

Title: Page 2
Area: Manchester

Title: Page 3
Area: Birmingham

I want to be able to loop through these:

London (links to /area:London/)

Manchester (links to /area:Manchester/)

Birmingham (links to /area:Birmingham/)

So I can create links from them.

You can use the pluck() function, which goes through all pages and plucks the values. If you want every value only once, you can use the unique flag.

$areas = $site->index()->pluck('area', null, true);

The you can loop through the collection and output each entry together with a link by which you can then filter.

Works perfectly. I’d seen Pluck around but didn’t think it applied here. Guess I’ll have to experiment with it a bit more. Thanks :smile:

Here’s the code I’ve used in case it helps anyone else:

<?php $areas = $site->index()->pluck('area', null, true);?>
    <?php foreach($areas as $area): ?>
       <a href="<?php echo $page->url().'/area:'. $area ;?>/"><?php echo $area;?></a>
    <?php endforeach ?>`