Last active
December 26, 2015 13:29
-
-
Save andyg5000/7158389 to your computer and use it in GitHub Desktop.
Entity Field Query and Entity Metadata Wrapper example: Updates the stock field on products from orders with a past a defined order id (in pending status). I had to write this because the stock rules became corrupt after a series of updates to the site.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$order_id = 10; | |
// Create the entity field query object. | |
$efq = new EntityFieldQuery(); | |
// Add the required filters to the query and execute it. | |
$result = $efq->entityCondition('entity_type', 'commerce_order') | |
->propertyCondition('order_id', $order_id, '>=') | |
->propertyCondition('status', 'pending') | |
->execute(); | |
if (!empty($result['commerce_order'])) { | |
// Loop through each of the results returned. | |
foreach ($result['commerce_order'] as $oid) { | |
$order = commerce_order_load($oid->order_id); | |
// Create a metadata wrapper for easy read/write operations on the entites. | |
$order_wrapper = entity_metadata_wrapper('commerce_order', $order); | |
// Loop through the commerce line items. | |
foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) { | |
$line_item = $line_item_wrapper->value(); | |
$product = $line_item_wrapper->commerce_product->value(); | |
// Proceed only if the product contains a stock field. | |
if (!empty($product->commerce_stock)) { | |
// Obtain the stock using the wrapper. | |
$stock = $line_item_wrapper->commerce_product->commerce_stock->value(); | |
if ($stock > 0) { | |
$update = ($stock - $line_item->quantity); | |
// Set the updated stock using the wrapper. | |
$line_item_wrapper->commerce_product->commerce_stock->set($update); | |
commerce_product_save($product); | |
} | |
} | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment