Automatically display pages selected from a structure field of another page

Hello, I am currently building a blog and I have a page for each author of an article. I want to show every article the author has written on this page. On the article page I have a simple structure field to select the author.

My problem is that as soon as I select an author for an article, the article will be shown on each page by each author and not only on the selected one.

My snippet for this looks like this:

<?php foreach(page("writers")->children() as $subpage): ?>

	<?php 
		$writer = $subpage->uri();
		
		$articles = page('articles')->grandchildren()->filter(function($child) use($writer) {
		  $articledetail = $child->writer()->toStructure();
		  return $articledetail->findBy('selectwriter', $writer);
		});
	?>
	
	<?php foreach ($articles as $article):?>
		<p><?php echo $article->title();?></p>
	<?php endforeach ?>
	
<?php endforeach ?>

Thanks for any help :slight_smile:

Is that on the single author page ? Or on the blog page? Any reason why you use a structure field to select a single author an the article page?

yes it’s a single author page… I was thinking about what could be the easiest way to select an author for the article and thought the structure field would be a good solution.

If it is a single author page, it doesn’t make sense to loop through all the author pages.

The structure field only makes things complicated. If you want to assign a single author, your best bet is a select field.

1 Like

okay. Not sure how use it, but I will give it a try :slight_smile:

fields:
  author:
    type: select
    options: query
    query: kirby.page('authors').children

Then you can filter your articles on the author page like this:

<?php
$authorArticles = page('articles')->children()->listed()->filterBy('author', $page->id());
foreach ($authorArticles as $article): ?>
<?= $article->title() ?>
<?php endforeach ?>
2 Likes

Nice! This worked pretty good… Thanks for this :slight_smile:

just one more question. I also want to show the name of the author and link to the authors page on the articles page. Of course this: <?= $page->author();?> outputs page/author. I was wondering if something on my select field is missing? or If I have to remove the page and / via php?

$author = page('authors')->find($page->author()->value()); // adapt id of authors page as required
echo $author->name(); // or whatever you have stored in your author page
2 Likes