WP_Query not always returning posts
-
Hello All,
I have had the following problem to deal with :
I created a cronjob to update the stock value of the products in our webshop. We get these values from our warehouse partner. So i created the following function to update the stock :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 with stock amounts keyed by the SKU of the product. When I run this cronjob from within the admin panel everything runs fine. When I let it run from within the cronjob itself, nothing happens when calling get_products(). The script simply ends at once without any error.
I have been digging into this problem today and found it to come from WP_Query->query(). Looking at this function, this is the code :
public function query( $query ) {
$this->init();
$this->query = $this->query_vars = wp_parse_args( $query );
return $this->get_posts();
}The scripts stop running after :
$this->query = $this->query_vars = wp_parse_args( $query );
When i split this function it happends at the moment $this->query is overwritten. As it seems PHP (I have version 7.2.11) can’t figure out if it needs to override the variable $query or the function query as the variable gets unset while initialising the function and wp_parse_args returns a pointer when you pass an array to it.
This naming scheme is not really handy when using a weak-typed language like PHP. Although I have no idea why PHP gets it wrong while running the cron and gets it right when triggering from the admin panel.
I renamed the variable $query to something else and changed all the occurences the script didn’t crash at the given line so the naming is really the problem. But I can’t simply rename since other parts of the WordPress code are dependent on this public variable of the class and all scripts call the ->query() function.
So I am a bit lost on how to fix this problem, but it stops my website from receiving the latest stock updated from out warehouse.
Please could some of the developers shed a light on this problem and how to fix it??
With kind regards,
Michel van der Breggen
- The topic ‘WP_Query not always returning posts’ is closed to new replies.