Search code examples
phpwordpressloopswoocommercewordpress-featured-image

How to show random featured products (woocommerce) in a WP custom loop?


I am trying to have a custom loop in Wordpress for Woocommerce products. I want to show a random featured product in the loop. But for some reason it doesn't get my arguments right and picks a random product from all products available.

This the code i'm using at moment. It does show a random product, but it ignores the featured part of the code.

$args = array(
    'posts_per_page'   => 1,
    'orderby'          => 'rand',
    'post_type'        => 'product',
    'meta_query'  => array(
        'key'     => '_featured',
        'value'   => 'yes'
    )
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

<li>
    <a href="<?php echo the_permalink(); ?>">
        <h3><?php the_title(); ?></h3>
    </a>
</li>

<?php endwhile;
wp_reset_query(); ?>

Can someone lead me into the right direction?

Thanks in advance!


Solution

  • I've just come across this,

    Its not directly for your issue, but could be the base of it.

    It seems featured items are no longer stored as meta:

        $meta_query  = WC()->query->get_meta_query();
        $tax_query   = WC()->query->get_tax_query();
        $tax_query[] = array(
            'taxonomy' => 'product_visibility',
            'field'    => 'name',
            'terms'    => 'featured',
            'operator' => 'IN',
        );
    
    $query_args = array(
        'post_type'           => 'product',
        'post_status'         => 'publish',
        'ignore_sticky_posts' => 1,
        'posts_per_page'      => 1,
        'meta_query'          => $meta_query,
        'tax_query'           => $tax_query,
    );`