Woocommerce is a awesome plugin, when building an e-commerce website for yourself and clients. We can use woocommerce with various popular themes. If you want to build your custom e-commerce website, then you can also use woocommerce template pages. From developer prospective, if you want to show products(post_type=’product’) related to any specific category , then below the below code reference.
This is an sample HTML section, where I would show latest products related to category ‘mobiles’.
In my woocommerce these are some categories. These are mobiles, decor, accessories etc.
Now, lets see about category(taxonomy) ‘Mobiles’. Here category name is ‘Mobiles’ and slug is ‘mobiles’. products related to this category from wp-admin here.
Now, let’s see below code about how to render all the products related to taxonomy slug ‘mobiles’.
<?php
$category_slug = 'mobiles';
// Query the posts in the specific category
$args = array(
'post_type' => 'product',
'posts_per_page' => 4,
'order_by' => 'date',
'tax_query' => array(
array(
'taxonomy' => 'product_cat', // Change to 'category' for regular blog posts
'field' => 'slug',
'terms' => $category_slug,
),
),
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$thumbnail = wp_get_attachment_image_src(get_post_thumbnail_id(), 'large');
$categories = get_the_terms(get_the_ID(), 'product_cat');
if ($categories && !is_wp_error($categories)) {
foreach ($categories as $category) {
$product_category = $category->name;
}
}
}
}
?>
Here is the below output for this …
Follow me !!
👉 My Social Media links
🤹♂️Linkedin: https://www.linkedin.com/in/shimanta-das-497167223
👹facebook : https://www.facebook.com/profile.php?id=100078406112813
📸Instagram : https://www.instagram.com/meshimanta/?hl=en
🐦Twitter : https://mobile.twitter.com/Shimantadas247
📬Telegram link : https://t.me/microcodesofficial
🎦Youtube : https://youtube.com/channel/UCrbf6B0CU9x-I4bQOYbJVGw
Top comments (0)