• Resolved breggen

    (@breggen)


    Hello All,
    I am pretty new to WordPress and WooCommerce but a 10+ years programmer of PHP applications. I am trying to master the inner workings of WordPress and WooCommerce for a small company.

    What I am trying to do is create a cronjob that synchronises the stock of woocommerce with the stock of our warehouse supplier. I created the following function :

    // Update the stock of our products every 10 minutes
    function cron_yp_update_product_stock_b1f6051b() {
    	$oConvexStock = YP_get_stock_per_SKU();
    	
    	$oQuery = new WC_Product_Query( array( "return" => "objects", "virtual" => false ) );
    	$oResult = $oQuery->get_products();
    	if ( is_array( $oResult ) ) {
    		foreach( $oResult as $oProduct ) {
    			if ( isset( $oConvexStock[$oProduct->get_sku()] ) ) {
    				wc_update_product_stock($oProduct, $oConvexStock[$oProduct->get_sku()], "set" );
    			}
    		}
    	}
    }

    This gets an array of stock with the SKU of the product as key. then finds all available products in woocommerce and once it finds a matching stock it will update the stock quantity in woocommerce. Doesn’t sound that hard.

    This all works fine when i run the cronjob from the admin panel. Takes a few seconds and all stock is up to date. But when the cronjob is triggered autonomous by wp_cron it seems WC_Product_Query is an empty object ( or rather an uninitialized object ) and if fails when calling get_product().

    Does anybody know why this is and how to get WooCommerce to load and init in the cron?

    With regards,
    Michel van der Breggen

Viewing 1 replies (of 1 total)
  • Plugin Contributor Peter Fabian

    (@peterfabian1000)

    Hi,

    sorry for late reply.

    I would say a better approach than using wp_cron could be to update the stock via REST API if you have the option to use that:
    https://woocommerce.github.io/woocommerce-rest-api-docs/#batch-update-products

    If that is out of the question, according to https://konstantin.blog/2013/tip-wp_cron-runs-during-init/, wp_cron runs at action init with priority 10, so I’ve tried 2 approaches:
    – created a function that uses WC_Product_Query and runs at init with priority 10
    – triggered WC_Product_Query via scheduled action in wp_cron (by visiting a page)

    In both cases I was able to get correct result, so it’s difficult for me to say what might be wrong in your case.

    I’d check at what point the function you use gets triggered. In case you need to force load WC, I suggest you have a look at class-wc-post-types.php and class-woocommerce.php. The code that registers post types and taxonomies should run before WC_Product_Query can return anything.

Viewing 1 replies (of 1 total)
  • The topic ‘WC_Product_Query not working with cron’ is closed to new replies.