Display Random Product Link

I need PHP-code for WordPress (Woocommerce) to display random product link.

For example, I have Product1 and want to display on this page (in description of my product):

Read More

“See also other products: [Product2 – link] and [Product3 – link]”

Don’t know how, I just need php code to insert it in post/pages/products and everywhere I want on my site.

I’m not a coder and I found this code, for example, to display page title with link, but it’s not what I need

<?php
echo '<a href="'.get_permalink($product_id).'">'.get_the_title($product_id).'</a>';
?>

But how to get random product, don’t know, thanks for help.

Related posts

2 comments

  1. Try this :

     $args = array(
        'posts_per_page'   => 1,
        'orderby'          => 'rand',
        'post_type'        => 'product' ); 
    
    $random_products = get_posts( $args );
    foreach ( $random_products as $post ) : setup_postdata( $post ); ?>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php endforeach; 
    wp_reset_postdata();
    
  2. The Perfect solution for outputting a single random product which can be achieved using the following code.

    <?php
    $post_array=array();
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12
            );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
                array_push($post_array,get_the_ID());
            endwhile;
            $random_key = array_rand($post_array, 1);
            echo '<a href="'.get_permalink($post_array[$random_key]).'">'.get_the_title($post_array[$random_key]).'</a>';
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>
    

    Have tested the same for you. It worked. Lemme Know if the same worked for you too.

Comments are closed.