Get a content field by its variable field name

Hey guys!
I was searching for an option to get some specific content by it’s field name – but with a variable field name. As hard as it is for me to describe the problem, as hard it is to search for a solution. So maybe you get the idea when you read my code:

<?php 
  $items = [
    "facebook",
    "twitter",
    "website"
  ]
?>
<?php foreach ($items as $item) : ?>
  <?php if ($page->content->has($item)) : ?>
    <a href="<?php echo $page->getContent($item) ?>">Some link</a>
  <?php endif; ?>
<?php endforeach; ?>

The $page->getContent() is just there to illustrate what i am searching for. $page->getContent() does not exist. Does anyone have an idea how to solve this?

That would be something like this:

<?php 
  $items = [
    "facebook",
    "twitter",
    "website"
  ];
?>
<?php foreach($items as $item): ?>
  <?php if($page->$item()->isNotEmpty()): ?>
    <a href="<?php echo $page->$item() ?>">Some link</a>
  <?php endif ?>
<?php endforeach ?>

If you don’t like the syntax, you can use the “official” way that is easier to understand but longer:

<?php 
  $items = [
    "facebook",
    "twitter",
    "website"
  ];
?>
<?php foreach($items as $item): ?>
  <?php if($page->content()->has($item)): ?>
    <a href="<?php echo $page->content()->get($item) ?>">Some link</a>
  <?php endif ?>
<?php endforeach ?>
3 Likes

This is it. Thank you!

Is there a way to use ->content() with an image? If I try the same thing with an image I get “ErrorException (E_ERROR) Call to a member function get() on a non-object”.

example code (which fails):

foreach ($page->images() as $i) {
echo $i->content()->get(‘somefield’);
}

Thanks.

Do all images in your $page->images() collection have a metadata file with fields?

For a file, it’s $file->meta().

Excellent. Thank you, $file->meta() is what I needed.