Loop / Iterate through all fields in a page

I’ve seen the question asked and answered around the forum, but I did not see this solution and I think it may be simpler:

<?php foreach( $page->content()->fields() as $f ): ?>
  <?= $page->$f() ?> <br />
<?php endforeach ?>

I use $page->content()->fields() to get an array of the page’s field NAMES; and then I loop that array, adding parentheses to each name. This seems to turn the field name into the field method, returning the full field object.

It also works with page(‘pagename’) :

<?php foreach( page('pagename')->content()->fields() as $f ): ?>
	<?= page('pagename')->$f() ?> <br />
<?php endforeach ?>

:slight_smile:

Does the above code work for you or why is it in the “solutions” category?

Actually the code that works for me is the following (I’ll edit the solution once it is clear):

<?php $p = page('pagename') ?>
<?php foreach( $p->content()->fields() as $f ): ?>
	<?= $p->$f() ?> <br />
<?php endforeach ?>

edit:

This works too:

<?php foreach( $page->content()->fields() as $f ): ?>
	<?= $page->$f() ?> <br />
<?php endforeach ?>

This also works:

<?php foreach( page('pagename')->content()->fields() as $f ): ?>
	<?= page('pagename')->$f() ?> <br />
<?php endforeach ?>

Full disclosure: I am not sure what I am doing.

All three are OK, but the first piece of code (in your first post) will not work, because there is no fields() page method. $page is the usual way of referring to the current page.

Yes, I missed content() , plus the colon after the foreach actually, heh.

I corrected the first post, I think now it is fully correct.