1

I want to create an array of all SKUs on Craft Commerce. The end goal is to create a plugin that only applies Sales to certain variants. It does this by checking the Sale's description for any mention of SKUs and comparing this against the list of all available SKUs.

I thought this would do the trick…

$allvariants = craft()->elements->getCriteria('Commerce_Variant');
$allskus = $allvariants -> sku;

But it doesn't appear to work. The full code of the plugin is…

craft()->on('commerce_sales.onBeforeMatchProductAndSale', function($event){
    $sale = $event->params['sale'];

    $allvariants = craft()->elements->getCriteria('Commerce_Variant');
    $allskus = $allvariants -> sku;

    if (stripos($sale->description, 'only') === false) {
       return; /* do nothing, and let the sale match as it normally would, because the sale does not have 'only' in the description. */
    } else {
        if (stripos($sale->description, $allskus) === false) {
            $event->performAction = false; /* since this SKU is not in the description string, then don't apply this discount */
        }
    }
});`

(Full credit to @luke-holder who wrote the plugin to do this for Discounts)

1

This should grab all of the variant's SKUs like you're looking for:

$criteria = craft()->elements->getCriteria('Commerce_Variant');
$allVariants = $criteria->find();
$allSkus = array();

foreach ($allVariants as $variant)
{
    $allSkus[] = $variant->sku;
}
2
  • Thanks Brad. That solved the first part of my question. But I had the wrong idea to fix the plugin. Stripos searches strings, and even if I changed the for loop to become a longer string, it didn't fix the plugin. I'll need to rethink this
    – Will Law
    Apr 17 '17 at 22:44
  • No pressure, but any possibility you could look at this question relating to the plugin mentioned above? — I'm at a loss on how to fix it.
    – Will Law
    Apr 18 '17 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.