Last active
September 12, 2024 14:58
-
-
Save StefsterNYC/bf9652dadb2a8e97c67b8dfb0ad261e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* @snippet Utilizes the Product Category Thumbnail to apply itself in place of the PDP's Main image on all products in that category. | |
* @author Serafin Tech | |
* @compatible WooCommerce 9+ | |
* @website https://serafintech.io | |
*/ | |
add_filter('woocommerce_product_get_image', 'use_category_thumbnail_if_no_product_image', 10, 3); | |
function use_category_thumbnail_if_no_product_image($image, $product, $size) { | |
if (!has_post_thumbnail($product->get_id())) { | |
$terms = get_the_terms($product->get_id(), 'product_cat'); | |
if ($terms && !is_wp_error($terms)) { | |
$category = $terms[0]; | |
$thumbnail_id = get_term_meta($category->term_id, 'thumbnail_id', true); | |
if ($thumbnail_id) { | |
$image = wp_get_attachment_image($thumbnail_id, $size); | |
} | |
} | |
} | |
return $image; | |
} | |
add_filter('woocommerce_single_product_image_thumbnail_html', 'replace_single_product_image_with_category_thumbnail', 10, 2); | |
function replace_single_product_image_with_category_thumbnail($html, $post_id) { | |
global $product; | |
if (!has_post_thumbnail($post_id)) { | |
$terms = get_the_terms($post_id, 'product_cat'); | |
if ($terms && !is_wp_error($terms)) { | |
$category = $terms[0]; | |
$thumbnail_id = get_term_meta($category->term_id, 'thumbnail_id', true); | |
if ($thumbnail_id) { | |
$image_url = wp_get_attachment_image_url($thumbnail_id, 'full'); | |
if ($image_url) { | |
return '<img src="' . esc_url($image_url) . '" alt="' . esc_attr($category->name) . '">'; | |
} | |
} | |
} | |
} | |
return $html; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is for those who want the product category thumbnail to apply to all PDPs in said category. Use at your own risk. Tested up to 6.6.2 core and WooCommerce 9.3 Code should be added to your functions.php file of your child theme