WooCommerce Loop

A loop checks to see if more products (for a specific condition) are left to display. If there are, the product details are grabbed from the database, rendered to screen, and the process then restarts or loops around until no more products are left to display.

<ul class="products">
	<?php
		$args = array(
			'post_type' => 'product',
			'posts_per_page' => 12
		);
		$loop = new WP_Query( $args );
		if ( $loop->have_posts() ) {
			while ( $loop->have_posts() ) : $loop->the_post();
				wc_get_template_part( 'content', 'product' );
			endwhile;
		} else {
			echo __( 'No products found' );
		}
		wp_reset_postdata();
	?>
</ul>

  1. The WP_Query object to set up the database query to get product data.

  2. The product search criteria are set from the $args array on lines 3-6.

  3. The query looks for post types β€˜product’, with page pagination set to return 12 products per page.

  4. wc_get_template_part() - is a woocommerce hook to get template part (for templates like the shop-loop). wc_get_template_part( $slug, $name );

  5. Make a message if there is no product in this case i use this message " No Products Found".

  6. wp_reset_postdata() After looping through a separate query, this function restores the $post global to the current post in the main query.

Last updated