We are transitioning over to a new forum platform. Please post new issues there. Existing threads will be dealt with here unless you choose to move them over. Visit the new forum

Forum

Thread tagged as: Question, Shop

Stock Level for Variants

Okay, so here's the issue. I'm surprised no one has run into this. My client sells hats, but the product could be anything like t-shirts. Each hat style has a color variant.

Well, I want to display if the product is in stock or not ... problem is, the client tracks the products by variant. Is there a way to show if the product is in stock by getting a count of all the variant stock numbers COMBINED?

In theory, if I count stock on individual variant, then the stock_level will always read zero ... if I set it to 1, then even if the client sells out all of variants, the stock level will still read 1 and show that we have that item in stock.

I feel like there's a disconnect between count stock on individual variant and the stock_level for the item as a whole. If you track count stock on individual variant then the stock_level should be auto-calculated as such.

I thought of a hack, in the template looping though all the variants and gathering their individual stock numbers and adding them together, but as far as I can tell, theres no way to do math inside a template.

Even then, if that did work, this would still fail or at least not match:

perch_shop_products([
        'filter' => 'stock_level',
        'match' => 'gte',
        'value' => '1'
    ]);

correct me if I'm wrong on all this ...

Blake Myers

Blake Myers 0 points

  • 2 years ago

so I found a hack for the first issue ... on the actual product page, I do this:

$count = 0;
$vars = perch_shop_product_variants($prod, [
    'skip-template' => true,
    'return-html' => false,
]);

foreach ($vars as $key => $value) {
    $count += $value['stock_level'];
}

PerchSystem::set_var('full_stock', $count);

perch_shop_product($prod, [
    'template' => 'products/list_individual.html',
    'variants' => true,
]);

obviously, passing the newly calculated stock number as a variable and calling it with <perch:shop id="full_stock" type="text" />

but I don't think this will work for a product listing page, where several products are listed and I call them all at once with perch_shop_products ... unless I can pass arrays into the templates as variables ... I guess I could try, but I don't see anything like that in the docs.

Drew McLellan

Drew McLellan 2638 points
Perch Support

On the listing page you'd need to use an each callback function to do the above.

I just want to chip in and say that I've had the same issue, and also agree with the statement; "If you track count stock on individual variant then the stock_level should be auto-calculated as such." The stock_level should also then be disabled I feel.

Would be a nice little update in a future update.