Skip to content
Advertisement

Display random products depending on category

I’m in the single product page of a product. I want to show, after this product, 4 other random products with the same category

All I have is this: (PHP)

<?php
        global $product;
        $terms = get_the_terms( $product->get_id(), 'product_cat' );

        var_dump($terms);
    $args = array(
        'posts_per_page'   => 4,
        'orderby'          => 'rand',
                'post_type'        => 'product' ); 

    $random_products = get_posts( $args );

    foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
    <li>
        <a href="<?php the_permalink(); ?>">
    <?php the_title(); ?></a>
    </li>
<?php endforeach; 
wp_reset_postdata();
?>

Can any one help me? Thanks

Advertisement

Answer

You can try this way. I checked it’s worked:

global $product;
    $terms = get_the_terms( $product->get_id(), 'product_cat' );
    $first_term = array_shift( $terms );

    $args = array(
        'posts_per_page'   => 4,
        'orderby'          => 'rand',
        'post_type'        => 'product',
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'slug',
                'terms'    => array( $first_term->slug )
            )
        ),
        'post__not_in' => array( $product->get_id() )
    );

    $random_products = get_posts( $args );

    foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
        <li>
            <a href="<?php the_permalink(); ?>">
                <?php the_title(); ?></a>
        </li>
    <?php endforeach;
    wp_reset_postdata();
    ?>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement