How to display featured products on the homepage? (Sage 9 / WooCommerce)

This isn’t tested, but you’d do something roughly like this with the filter approach.

First, in filters.php, fetch your products and add them to the data that’s passed to your template:

add_filter('sage/template/front-page/data', function (array $data) {
    $args = array(
        'post_type' => 'product',
        'posts_per_page' => 12,
        'tax_query' => array(
            array(
                'taxonomy' => 'product_visibility',
                'field'    => 'name',
                'terms'    => 'featured',
            ),
        ),
    );
    $data['products'] = new WP_Query($args);
    return $data;
});

If your page doesn’t have the front-page class on the body element, replace front-page with the appropriate class.

Then in your Blade template:

@if (!$products->have_posts())
  {{ __('No products found') }}
@endif

@while ($products->have_posts()) @php $products->the_post() @endphp
  @php wc_get_template_part('content', 'product') @endphp
@endwhile
@php wp_reset_postdata() @endphp

@alwaysblank is a wizard when it comes to doing this stuff cleanly

4 Likes