Filter articles by subject

Hello I want to show only the articles with the subject name “nutrition” when the $_POST[‘nutrition’] is set.
I got this

<?php 
    if(isset($_POST['nutrition'])){ 
?>
<section class="content cf">
	<?php foreach($articles as $article): ?>
	<article class="articles">
		<h2>
            <a href="<?php echo $article->url() ?>"><?php echo $article->title()->html() ?></a>
        </h2>
		<time datetime="<?php echo $article->date('c') ?>" pubdate="pubdate"><?php echo $article->date('d.m.Y') ?></time>  |  <?php echo $article->subject() ?>
        
        <?php if($article->hasImages()){?>
                    <img src="<?php  $img = $article->banners();
                    echo $article->url() . "/" . $img;
                  ?>" style="border-bottom: 5px solid  <?php $prev = $article; $color = $prev->color(); echo $color; ?>"><?php } ?> 
	</article>
	<?php endforeach ?>

but this shows all the articles but I want to show only the ones with the subject nutrition.

Does anyone have an idea how I can do so.

You can use filterBy(). Check the docs and this cookbook recipe.

The best place for this is in a controller.

Something like:

<?php

return function($site, $pages, $page) {

  // get all articles and add pagination
  $articles = $page->children()->visible();

  // add a filter
  if($filter = get('nutrition')) {
    $articles = $articles->filterBy('subject', '=', $filter, ',');
  }


  // pass $articles and $pagination to the template
  return compact('articles', 'filter');

};

Thanks for the quick response it works now thank you.