Forum

Thread tagged as: Question

Passing vars into individual collection items

Hi Guys,

I have a list page that shows all items for a collection. Individually I am able to pass in a perch var, like so:

if (perch_get('product_slug')) {
    $result = perch_collection('Products', array(
        'template'          => 'shop/product',
        'filter'            => 'product_slug',
        'match'             => 'eq',
        'value'             => perch_get('product_slug'),
        'count'             => 1,
        'skip-template'     => true,
        'return-html'       => true,
    ));
PerchSystem::set_var('total_price', ($result[0]['product_price']+$result[0]['product_postage'])*100);
}

However, on the main page where all the items are listed. How can I pass/set this var individually for each collection item?

    perch_collection('Products', [
        'template'          => 'shop/_teaser',
    ]);

Thanks, Terry

Terry Upton

Terry Upton 0 points

  • 5 years ago
Drew McLellan

Drew McLellan 2638 points
Perch Support

Use an each callback. See the section "Specifying an item callback function"

https://docs.grabaperch.com/docs/content/perch-content-custom/

I have tried this;

perch_collection('Products', [
                'template'          => 'shop/_teaser',
                'each' => function($item) {
                    PerchSystem::set_var('total_price', ($item['product_price']+$item['product_postage'])*100);
                    return $item;
                },

But it sets the same amount for each product. Rater than each one individually. My code might be wrong, any pointers?

Thanks Drew.

Terry

Drew McLellan

Drew McLellan 2638 points
Perch Support

You need to modify $item and then return it, so instead of this:

PerchSystem::set_var('total_price', ($item['product_price']+$item['product_postage'])*100);

do this:

$item['total_price'] = ($item['product_price']+$item['product_postage'])*100;

Thanks Drew :-)