How to Display woocommerce Products by custom code
In this tutorial, we discussed how to display woocommerce products with your custom HTML or with a simple layout.
The Basic Code
//developers guidance
<?php
$params = array('posts_per_page' => 5, 'post_type' => 'product');
$wc_query = new WP_Query($params);
?>
<?php if ($wc_query->have_posts()) : ?>
<?php while ($wc_query->have_posts()) :
$wc_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p>
<?php _e( 'No Products'); ?>
</p>
<?php endif; ?>
Display Woocommerce Products category wise:
The below code help to display the woocommerce products
<?php
$products = wc_get_products(array('category' => array('category_slug'),);
foreach ($products as $value) {?>
<?php } ?>
You can add more conditions as per the requirement in-display woocommerce products.
‘limit’ => 8, ‘order’ => ‘ASC’, etc
for example :
<?php $products = wc_get_products(array('category' => array('dumbbells'),'order' => 'ASC',);foreach ($products as $value) {?><?php}?>
USING ABOVE CODE HOW TO DISPLAY IMAGE, NAME ETC.
Display Image: <?=wp_get_attachment_url($value->image_id );?>
Display Name : <?=(wp_strip_all_tags($value->name), 7, ‘…’?> or <?=$value->name?>
Display Price : <?=$value->price;?>
Product Url : <?=$value->slug?>
Basic Functions to display woocommerce products
- the_title() : Display the product name
- the_excerpt() : Display the brief description about the product
- the_content() : Dispaly the full description of the product
- the_permalink() : Dispay the product URL
- the_post_thumbnail() : Display product image
- the_ID() : Display product ID