Skip to content

Instantly share code, notes, and snippets.

@andyg2
Created January 26, 2026 04:01
Show Gist options
  • Select an option

  • Save andyg2/97988a9589f6c6727f9a3fc992562571 to your computer and use it in GitHub Desktop.

Select an option

Save andyg2/97988a9589f6c6727f9a3fc992562571 to your computer and use it in GitHub Desktop.
Woocommerce: Shows a random product image for product categories without a category image (frontend only).
<?php
/**
* Plugin Name: DGTE WC Category Image Fallback
* Description: Shows a random product image for product categories without a category image (frontend only).
* Version: 1.0
* Author: Andy Gee
* Author URI: https://github.com/andyg2
*/
if (! defined('ABSPATH')) {
exit;
}
// Frontend only
add_action('wp', function () {
if (is_admin()) {
return;
}
// Remove default WooCommerce category thumbnail output
remove_action(
'woocommerce_before_subcategory_title',
'woocommerce_subcategory_thumbnail',
10
);
// Add our replacement
add_action(
'woocommerce_before_subcategory_title',
'dgte_random_category_thumbnail',
10
);
});
function dgte_random_category_thumbnail($category) {
$size = apply_filters('subcategory_archive_thumbnail_size', 'woocommerce_thumbnail');
$dimensions = wc_get_image_size($size);
// If category already has a thumbnail, use it normally
$thumbnail_id = get_term_meta($category->term_id, 'thumbnail_id', true);
if ($thumbnail_id) {
echo wp_get_attachment_image(
$thumbnail_id,
$size,
false,
[
'alt' => esc_attr($category->name),
'width' => esc_attr($dimensions['width']),
'height' => esc_attr($dimensions['height']),
]
);
return;
}
// Get one random product with a featured image
$product = get_posts([
'post_type' => 'product',
'posts_per_page' => 1,
'orderby' => 'rand',
'tax_query' => [
[
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category->term_id,
],
],
'meta_query' => [
[
'key' => '_thumbnail_id',
'compare' => 'EXISTS',
],
],
'no_found_rows' => true,
]);
if (empty($product)) {
return;
}
echo get_the_post_thumbnail(
$product[0]->ID,
$size,
[
'alt' => esc_attr($category->name),
'width' => esc_attr($dimensions['width']),
'height' => esc_attr($dimensions['height']),
]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment