Example query for returning a loop of 4 random products, logic is added to App.php, only output content is added to the blade file.
public function related_products()
{
$products = get_posts([
'post_type' => 'product',
'posts_per_page' => 4,
'orderby' => 'rand',
]);
return array_map(function ($post) {
return [
'title' => get_the_title($post->ID),
'link' => get_the_permalink($post->ID),
];
}, $products);
}
@if ( !empty( $related_products ) )
<div class="related-products woocommerce">
<ul class="products columns-4">
@php $i = 0 @endphp
@foreach ( $related_products as $product )
<li class="product @if ( $i == 0 ) first @elseif ( $i == 3 ) last @endif">
<a class="woocommerce-LoopProduct-link woocommerce-loop-product__link" href="{!! $product['link'] !!}">
<h2 class="woocommerce-loop-product__title">{!! $product['title'] !!}</h2>
</a>
<a class="button" href="{!! $product['link'] !!}">Read more</a>
</li>
@php $i++ @endphp
@endforeach
</ul>
</div>
@endif