2

So, here is the woocommerce setting that I have.

  1. I have three categories: A, B and C.

  2. From the backend, I gave category images to each categories.

Now, let say I post a product in the category A without selecting any images.

The product just shows the woocommerce default image (the one with the grey background).

Is there a way to use the category images as the default product image when there is no image selected?

Thanks

3

The code for changing the default image is provided by WooCommerce in this link but for your requirement we have to customize the code as follows

    /*
    * goes in theme functions.php or a custom plugin. Replace the image filename/path with your own :)
    *
    **/
add_action('init', 'custom_fix_thumbnail');

function custom_fix_thumbnail() {
    add_filter('woocommerce_placeholder_img_src', 'custom_woocommerce_placeholder_img_src');

    function custom_woocommerce_placeholder_img_src($src) {
        if (is_shop() || is_singular('product') || is_archive() || is_checkout() || is_cart()) {
            global $post;
            $array = get_the_terms($post->ID, 'product_cat');
            reset($array);
            $first_key = key($array);
            $thumbnail_id = get_woocommerce_term_meta($first_key, 'thumbnail_id', true);

            // get the image URL for parent category
            $image = wp_get_attachment_url($thumbnail_id);

            // print the IMG HTML for parent category
            if ($image)
                $src = $image;
        }
        return $src;
    }

}

There are some limitation for this code which i provided. A product may have more than 1 categories assigned in this code i am using the image of the first category which i get.

Customize the if condition i.e. add and remove condition's parameter according to your needs.

  • This uses "woocommerce_placeholder_img_src" but that function is depreciated no? docs.woocommerce.com/wc-apidocs/… – cchiera Jan 22 '17 at 20:14
  • The function has been deprecated and replaced with "wc_placeholder_img_src". However, the filter still uses "woocommerce_placeholder_img_src". – David Oct 23 '17 at 21:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.