In WooCommerce, a category is used to classify a product. Some e-stores need categories, instead of the products, to be displayed on the shop page. It’s basically the case, when a product search is driven by the category. It’s like when you go to a supermarket. You usually tend to look at the sections and then decide where to head. Say you want to buy soap. You head on to the soap section and then pick out the brand you want (which is the actual product). Categories help you narrow down your search, in a fairly quick and logical way.
Design of the Shop Page
Using WooCommerce, we can set up categories on the shop page, instead of products. When a visitor lands on the shop page, only the categories can be shown. Upon clicking a particular category, the list of products under the category will be shown.
Modification to Show Product List on Hover
In a client project, the products linked to a category were few. Hence instead of waiting for the user to click the category and then display the products, the requirement was to show the product list, when the user hovered on a particular category image.
In this case, you are not redirected to a new page with the products. The product list is shown on the same Shop page, when the user hovers on a category. To achieve this, we need to first get the list of products associated with each category.
Fetching the list of Products for a Category
The WooCommerce loop will display the categories on the shop page. During this we can also get the product associated with the category. We can then use the product data we need, like title and link.
// $category refers to the current category in the loop
$term_id = $category->slug;
$ps_info = $wpdb->get_results(“SELECT post_title, ID FROM $posts p LEFT OUTER JOIN $term_rel r ON r.object_id = p.ID LEFT OUTER JOIN $terms t ON t.term_id = r.term_taxonomy_id WHERE p.post_status = ‘publish’ AND p.post_type = ‘product’ AND t.slug = ‘$term_id'”);
foreach($ps_info as $ps)
// get the product link and title
$purl = get_permalink($ps->ID);
$ptitle = $ps->post_title;
Displaying the Associated Products
The Product list can be displayed using a div which will be hidden, till the user hovers over the category. Depending on the requirement, you can position the div, either over the category or besides it. You could read our article, On how to display an overlay on an image, to display the products list as text overlay on a category image.
Leave a Reply