Woocommerce random product image

I am trying to add an image onto my website that when pressed it loads up a random product in a different page. I added my code onto another website and someone added something for me but it still did not work for me. any help would be great.

// Get a random product (array with one value)

$random_product_id_array = get_posts( array(
‘posts_per_page’ => 1,
‘post_type’ => ‘product’,
‘orderby’ => ‘rand’,
‘fields’ => ‘ids’
) );

// Get the first value from the array (the random product ID)
$random_product_id = reset($random_product_array);

// Output
echo ‘’;

and the shortcode

add_shortcode('random_img_link', 'display_random_img_link');

function display_random_img_link() {
// Get a random product (array with one value)
$random_product_id_array = get_posts( array(
‘posts_per_page’ => 1,
‘post_type’ => ‘product’,
‘orderby’ => ‘rand’,
‘fields’ => ‘ids’
) );

// Get the first value from the array (the random product ID)
$random_product_id = reset($random_product_array);

// Output (always return)
return '<a href="'.get_permalink($random_product_id).'"><img alt="mylink" src="https://www.mylink.com/images/promo-pic.png" class="img" width="150" height="70"></a>';

}

shortcode was [random_img_link]


<?php
$args = array(
	'post_type' => 'product',
	'post_status' => 'publish',
    'orderby' => 'rand'
);

$random_product = new WP_Query($args);

if($random_product->have_posts()) {
	while($random_product->have_posts()) {
		$random_product->the_post();
 
		// Get product image
		$image_url = wp_get_attachment_image_src( get_post_thumbnail_id( get_the_ID() ), 'single-post-thumbnail' );
 
		// Get product URL
		$product_url = get_permalink( get_the_ID() );
 
		// Get product price
		$product = new WC_Product( get_the_ID() );
		$price = $product->get_price_html();
 
		// Output
		echo '<div>';
		echo '<img src="' . $image_url[0] . '" />';
		echo '<a href="' . $product_url . '">' . get_the_title() . '</a>';
		echo $price;
		echo '</div>';
	}
}
wp_reset_query();
?>
Sponsor our Newsletter | Privacy Policy | Terms of Service