mindkomm / timber-integration-woocommerce

WooCommerce integration for Timber
MIT License
107 stars 20 forks source link

woocommerce_shop_loop getting fired twice #42

Open will-yellowpeach opened 1 month ago

will-yellowpeach commented 1 month ago

In Product.php on line 71, the integration is firing the woocommerce_shop_loop action again meaning that any functions hooked to that are being duplicated. Is there a reason why that is there?

We have a component that is loaded in on that action and therefor it's currently being loaded twice. When we comment out line 71, it's only loaded once as expected.

Thanks

gchtr commented 1 month ago

The default WooCommerce template archive-product.php where the hook woocommerce_shop_loop is called looks like this:

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' );
    }
}

In the Twig equivalent in https://github.com/mindkomm/timber-integration-woocommerce/blob/1.x/defaults/archive-product.twig, that part looks like this:

{% if fn('wc_get_loop_prop', 'total') %}
    {% for post in posts %}
      {##
       # Depending on your WooCommerce display settings, the
       # `woocommerce_product_subcategories` function might reset the $wp_query global. By
       # calling `have_posts()`, we check if there are posts we can display.
       #}
      {% if fn('have_posts') %}
            {{ fn('wc_get_template_part', 'content', 'product' ) }}
      {% endif %}
    {% endfor %}
{% endif %}

As you can see, there’s no woocommerce_shop_loop there. There’ some magic in {% for post in posts %} that will call $post->setup() for each iteration of the for-loop. I placed the woocommerce_shop_loop hook in there, because I thought that is cleaner.

But as I’ve come to realize over the years, stuff like this can lead to problems like yours and doing things that I thought are very clever are sometimes not 😆. I’m trying to better understand this before I take any action.

So to confirm why this happens to you, could you answer the following questions?

will-yellowpeach commented 1 month ago

Thanks @gchtr.

So we're not including the archive-product.twig in our theme. All we are overriding it the content-product so just have content-product.twig in our theme, in order for us to load the product cards in templates outside of WooCommerce pages.

Your explanation makes sense in this scenario, as we're presumably using the default archive-product.php which has the woocommerce_shop_loop action in, plus then your 'setup' method is then firing it again. Perhaps that 'setup' method can check to see if that action has already run or if the archive-product.twig is being loaded in the theme?