phpwordpresswoocommercehook-woocommerce

Using woocommerce_loaded hook after data migration to fix variations


We have just mirigated nearly 6k products over from the live site. We are experiencing similar issues to the following post: Woocommerce: function to update all products. I've tried the fix mentioned in the post but it does not seem to fire when I go a product page. I've used query monitor and it is listing my call under the woocommerce_loaded hook but it does not fire.

Trying to solve the issue I created a new site on my dev machine with 1 product with the storefront theme and then created a child theme. In my functions.php I added the following code to see if the hook is fired:

add_action( 'woocommerce_loaded', 'update_products_by_x_childtheme' );
function update_products_by_x_childtheme()
{
     error_log("update_products_by_x_childtheme called when woocommerce_loaded in functions.php");
}

After enabling debugging it didn't write anything into the log. Query monitor listed my hook against the correct hook.

As the orginal post is over 5 years am I doing something wrong.

I also tried creating a plugin with the following methods:

public function AddActions() : void
{
   add_action( "woocommerce_loaded", array($this,"update_products_by_x_plugin") );
}

public function update_products_by_x_plugin() : void
{
    error_log("update_products_by_x_plugin called when woocommerce_loaded in plugin");
}

Output : [10-Jul-2024 12:40:56 UTC] update_products_by_x_plugin called when woocommerce_loaded in plugin

The plugin approach does work however it writes into the error log twice.

Could someone please explain why the plugin approach works and the code in the functions.php does not.


Solution

  • The function update_products_by_x_childtheme in the child theme fires after WooCommerce loads. See the attached image to understand how WordPress Loads.

    You can see themes are loading after plugins. So, the point here is that hook woocommerce_loaded fires as soon as Woocommerce Loads. So, woocommerce_loaded also does not fire for the plugins that come after the Woocommerce Loads.

    You can also try the following hooks. These hooks are fired in steps as I represented here:

    plugins_loaded -> setup_theme -> after_setup_theme -> init -> and wp_loaded
    

    enter image description here