I am trying to pull a random product thumbnail to display as an image on one of my pages. I can't seem to find a way that works, and have tried the solutions from this and this post.
It would be beneficial to echo it out in a div as well.
Here is what I am currently trying but I'm still unsure how to do this.
functions.php:
function get_random_thumbnails_for_reg(){
if(is_page(381)){
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => 'allison-1000-gm-duramax-series'
)
)
);
$random_products = get_posts( $args );
foreach ( $random_products as $post ) : setup_postdata( $post );
?>
<div id="randomPic"><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a></div>
<?php
endforeach;
wp_reset_postdata();
}
}
add_action('wp_footer', 'get_random_thumbnails_for_reg', 50);
Ok after some testing I got it working in a different modular way. I have created a custom shortcode that displays randomly one product thumbnail based on a product category**.
This shortcode has 2 argument:
cat
size
(can be:'shop_thumbnail'
,'shop_catalog'
or'shop_single'
)Then I use this short code in your custom function hooked in
wp_footer
action hook.Here is that code:
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
This code is tested and works