How to get a list of WooCommerce products (with shortcode)

Fetching a list of some or all of your WooCommerce products and displaying them on a page is easy. It involves a simple WordPress Query which is used to fetch the products and a then some PHP code to output it to the page.

Let’s have a look at the query to fetch the products and then the code to display it.

<?php
// Fetch the products.
$products = new WP_Query( array(

   /*
    * We're limiting the results to 100 products, change this as you
    * see fit. -1 is for unlimted but could introduce performance issues.
    */
   'posts_per_page' => 100,
   'post_type'      => 'product',
   'post_status'    => 'publish',
   'order'          => 'ASC',
   'orderby'        => 'title',

   ) );
?>

<ol>
   <?php
   while ( $products->have_posts() ) :
      $products->the_post();
   ?>
   
   <li><?php the_title(); ?></li>
   
   <?php
   endwhile;
   wp_reset_postdata();
   ?>
</ol>

List of WooCommerce products shortcode

Taking the above code snippet a bit further, we can create a shortcode which can be used on any post, page or custom post type to display the list of products on the page. Here is the code that is needed for the shortcode.

<?php
/**
 * Returns a product list of WooCommerce products. Intended to be called
 * by a shortcode `[thenga_product_list]`.
 *
 * @return string
 */
function thenga_render_product_list() {
   // Fetch the products.
   $products = new WP_Query( array(

      /*
       * We're limiting the results to 100 products, change this as you
       * see fit. -1 is for unlimted but could introduce performance issues.
       */
      'posts_per_page' => 100,
      'post_type'      => 'product',
      'post_status'    => 'publish',
      'order'          => 'ASC',
      'orderby'        => 'title',

   ) );

   $html = '<ol>';

   while ( $products->have_posts() ) {
      $products->the_post();

      $html .= sprintf(
         '<li><a href="%1$s">%2$s</a></li>',
         esc_url( get_the_permalink() ),
         esc_html( get_the_title() )
      );
   }

   $html .= '</ol>';

   wp_reset_postdata();

   return $html;
}
add_shortcode( 'thenga_product_list', 'thenga_render_product_list' );

Drop this in your functions.php file or in your theme or plugin, and you can now start using the shortcode [thenga_product_list] in any post, page or post type to display a list of you products.

Notice that in this shortcode example, we’ve added links to the products. You can play around with this as much as you like and even add product data to the mix.

Hope you found this useful. As always, let us know in the comments if you’re having any issues.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.