Search code examples
phpwordpresswoocommercehook-woocommercewoocommerce-theming

Why doesn't the product loop work outside of the archive-product.php file?


I'm playing around with creating a custom e-commerce site and I want to display some products on another page.

When I copy this loop from the archive-product page to my target page, it doesn't output anything

<?php
if (woocommerce_product_loop()) {

    woocommerce_product_loop_start();

    if (wc_get_loop_prop('total')) {
        while (have_posts()) {
            the_post();

            /**
             * Hook: woocommerce_shop_loop.
             */
            do_action('woocommerce_shop_loop');

            wc_get_template_part('content', 'product');
        }
    }

    woocommerce_product_loop_end();

    /**
     * Hook: woocommerce_after_shop_loop.
     *
     * @hooked woocommerce_pagination - 10
     */
    do_action('woocommerce_after_shop_loop');
} else {
    /**
     * Hook: woocommerce_no_products_found.
     *
     * @hooked wc_no_products_found - 10
     */
    do_action('woocommerce_no_products_found');
}
?>

What I know so far is that woocommerce_product_loop() returns true (1) but the wc_get_prop('total') returns a 0 which is in line with the default values of wc_setup_loop() which is called in wc_get_loop_prop() before returning true or false. I cannot find wc_setup_loop() being called before we start the archive-product.php products loop so why do things work there but not on my target page; aside from the surrounding HTML, and a few actions, the code is similar.

The reason I just want to copy and paste this code is experimentation, it's just driving me nuts that it won't work on a fresh page.

If it helps, my page is just like this

<?php get_header();?>
<div>
  <!-- paste code here -->
</div>
<?php get_footer();?>

NOTE: I'm a php newbie


Solution

  • the global posts for the archive is set to products post type and when you create a separate page or page-template there is no way to know what you wanna display here for that very reason we use WP_Query, you can read this article