I’m trying to update the category list/loop in woocommerce to replace the category thumbnail with a thumbnail of the newest available product in the respective category.
I think I’m halfway to achieve this on a test page though I can list the latest product of each category and display the category name beneath the image though I can’t get it to link to the category page. This is running on a test page though I would like it to work on the shop landing page.
Also for some reason I can’t get this to display as the regular woocommerce product grid. All the products/categories just stack even though I have replicated the woocommerce classes.
Here is the code. Am I going the long way around is there an easier way to achieve this?
<?php
if (is_page( 2295 )){ ?>
//open
<div class='woocommerce'>
<?php
//parameters for the function
$args = array(
'number' => $number,
'orderby' => 'title',
'order' => 'ASC',
'hide_empty' => $hide_empty,
'include' => $ids
);
//fetch the product categories
$product_categories = get_terms( 'product_cat', $args );
//how many categories
$count = count($product_categories);
// Check categories exist
if ( $count > 0 ){
//loop through and minipulate
foreach ( $product_categories as $product_category ) {
//parameters for the query
$args = array(
'posts_per_page' => 1,
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'product_cat',
'field' => 'slug',
'terms' => $product_category->slug
)
),
'post_type' => 'product',
'orderby' => 'title,'
);
//run the query with the above arguments
$products = new WP_Query( $args );
//open the list with woocommerce class
echo "<ul class='products columns-4'>";
//list latest products of each category
while ( $products->have_posts() ) {
$products->the_post();
?>
<li class="product-category product">
<a href="<?php get_site_url() ?>/product-category/<?php echo $product_category->slug; ?>">
<?php the_post_thumbnail('shop_catalog'); ?>
<?php echo"<h2 class'woocommerce-loop-category__title'>" . $product_category->name . "</h2>"; ?>
</a>
</li>
<?php
}
echo "</ul>";
}
}?>
</div>
<?php }
?>
Any help with this this would be awasome
2
Answers
If I also want to check if the product is in stock or not I have tried upating the query to something like this though looks to have broken something:
Add the follows code snippet in your active theme’s functions.php to achieve the above –