Posted Wednesday, December 21st, 2022 - 1,289 views
As SEOs we want to take advantage of all the WooCommerce customization options available through custom coding so we can provide users with the best experience possible. With this fix, you can paste the following code into the template that lists your products and if that product has subcategories, it will list them with their associated thumbnail.
If there is no thumbnail for the subcategory it will simply display the subcategory name. For the sake of SEO purposes, I suggest you get thumbnails into all those subcategories, name the images exactly what they are, and fully implement the script once all the thumbnails are in.
Update: The code includes a style element that sets the width, height, and object-fit properties for the subcatimage class. These styles make the thumbnail images fit inside the specified dimensions and preserves their aspect ratio so all the images look need and conformed.
Simply copy this code into the WordPress theme file you’re working with that displays your product categories.
if ( is_product_category() ) { $term_id = get_queried_object_id(); $taxonomy = 'product_cat'; $terms = get_terms([ 'taxonomy' => $taxonomy, 'hide_empty' => true, 'parent' => get_queried_object_id() ]); $output = '<style> .subcatimage { width: 150px; height: 150px; object-fit: cover; } </style>'; $output .= '<div><ul class="subcategories-list">'; foreach ( $terms as $term ) { $category_thumbnail_id = get_term_meta($term->term_id, 'thumbnail_id', true); $term_link = get_term_link( $term, $taxonomy ); if ( $category_thumbnail_id ) { $image_src = wp_get_attachment_url($category_thumbnail_id); $output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'"><img class="subcatimage" src="'.$image_src.'" alt="'.esc_attr($term->name).'">'. $term->name .'</a></li>'; } else { $output .= '<li class="'. $term->slug .'"><a href="'. $term_link .'">'. $term->name .'</a></li>'; } } echo $output . '</ul><div class="clear"></div></div><hr/>'; }
Leave a comment if you have any questions.
Leave a Reply