One of the conditions in my if statement does not work anymore when the if statement is inside a foreach statement. I understand where does the issue come from, but don't know how to solve it:
The aim is to have the list of blog articles written by John Doe, displayed on his biography page.
It worked when I directly wrote the author's name in the if condition:
<!-- current page: biography page -->
<div id="list_of_articles_by_John_Doe">
<?php foreach(page('magazine')->children() as $article): ?>
<?php if($article->author() == 'John Doe'): ?>
<p><?php echo $article->title() ?></p>
<?php endif ?>
<?php endforeach ?>
</div>
But I would like to automate the process, for each writer's biography page to have their own list of articles.
I tried to have as a condition the author of the current biography page ($page):
<!-- current page: biography page -->
<div id="automatic_list_of_articles">
<?php foreach(page('magazine')->children() as $article): ?>
<?php if($article->author() == $page->author()): ?>
<p><?php echo $article->title() ?></p>
<?php endif ?>
<?php endforeach ?>
</div>
but it makes another issue: it does not work because inside the foreach statement, $page->author()
(condition in the if statement) does not echo the author once, but one time for each page('magazine')->children() as $article
.
The condition if($article->author() == $page->author())
does not work in this example, as $page->author()
is not strictly the writer's name.
I'm wondering how to call $page->author()
to echo the writer's name only once, when inside the foreach statement.
endif
has a;
at the end like:endif;
(for foreach and your echo statement too btw) See: php.net/manual/en/control-structures.alternative-syntax.php$page->author()
? It sounds like that's where your issue is. I'm guessing you have a loop in there...?$page->author()
is Kirby CMS method that echoes the author of the page (which is stored as a text file) and$page
allows to echo different elements such as$page->title()
or$page->children()
;
is absolutely unnecessary, because?>
has equivalent effect.