Displaying a Custom Post Loop within a Custom Taxonomy Loop

Hey folks, I have the following controller which is returning exactly what I need to my custom template…

Collection 1
Recipe
Recipe
Recipe

Collection 2
Recipe
Recipe
Recipe

I just want to make sure that I have gone the right way around this. It does seem a little clunky based on the cleanliness of everything else Sage!!! Any feedback would so be appreciated :slight_smile:

class TemplateRecipes extends Controller
{

  protected $acf = true;

  public function collectionLoop() 
  {
    $collection_items = get_terms( 'collection', array(
      'orderby' => 'name',
      'hide_empty' => true,
    ));

    return array_map(function ($term) {
      return [
        'name' => $term->name,
        'slug' => $term->slug,
      ];
    }, $collection_items);
  }

  public function recipeLoop()
  {

    $collectionArr = $this->collectionLoop();

    $recipe_items = array();

    foreach ($collectionArr as $collection) {

      $recipe_posts = get_posts([
        'post_type' => 'recipe',
        'posts_per_page'=>'3',
        'tax_query' => array(
          array(
            'taxonomy' => 'collection',
            'field' => 'slug',
            'terms' => $collection
          )
        )
      ]);

      $recipe_items[] = array(
        'name' => $collection['name'],
        'slug' => $collection['slug'],
        'recipes' => array_map(function ($post) {
          return [
            'title' => apply_filters('the_title', $post->post_title),
            'thumbnail' => fly_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), array( 300, 300 ), true ),
            'url' => get_permalink($post->ID)
          ];
        }, $recipe_posts),
      );

    }

    return $recipe_items;
  }

}
1 Like

This topic was automatically closed after 42 days. New replies are no longer allowed.