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]

Sponsor our Newsletter | Privacy Policy | Terms of Service