Custom Post Types in loop

I’d recommend using a different variable than $loop here, since Blade uses $loop (for some pretty neat stuff) and you might see odd behavior if you’re overwriting it.

My personal opinion on best practices here is that you should extract as much logic as you can from your Blades to your controller (assuming you’re using soberwp/controller). I usually prefer to isolate custom queries completely by putting them in controller methods and then returning arrays that I iterate over in my Blades. The downside to that approach is that you don’t have access to functions like the_content() inside those loops, but for relatively trivial stuff IMO the pros usually outweigh the cons.

That might look like this:

// controllers/FrontPage.php
public function galleryLoop()
{
    $gallery_items = get_posts([
        'post_type' => 'gallery',
        'posts_per_page'=>'10',
    ]);

    return array_map(function ($post) {
        return apply_filters('the_content', $post->post_content);
    }, $gallery_items);
}

// views/front-page.blade.php
@foreach($gallery_loop as $gallery_item)
    {!! $gallery_item !!}
@endforeach

(Not 100% sure this code will work as written—I haven’t tested it—but it should provide a starting point.)

7 Likes