Plugin with structured fields, I cannot seem to make it work

I have basic understanding of php and having a problem.
Want to create a plugin to show structured fields.

The structured field located in ‘products.yml’, works great in the panel.
Schermafbeelding 2020-12-18 om 08.57.19

With the plugin I want to call the structured fields from the ‘products’ in markdown using the tag ‘(shopping-hero:)’

I created a plugin using the cookbook.
So far I can get everything from the ‘products’ but not the individual structured fields.

<?php
Kirby::plugin('your/shopping-hero', [
    'tags' => [
        'shopping-hero' => [

            'html' => function($tag) {

              return '' . $tag->parent()->products() . '';
            }]
    ]
]);

I am aware that this only returns the complete ‘products’ and not the individual structured fields within ‘products’. I have searched hours on the forums and tried to add functions $tag->toStructure(); etc. but haven found a working solution yet.

The structured fields in ‘products’ include ‘subtitle’, ‘tagline’, ‘shopprice’, etc.

Any assistance would be brilliant. Thank you.

You have to call toStructure() on the products field, then loop through the collection like you would in a template. Have you tried this?

$products =  $tag->parent()->products()->toStructure();
1 Like

Thank @pixelijn you for your response.
Unfortunately it returns empty, used this code now.

<?php
Kirby::plugin('your/shopping-hero', [
    'tags' => [
        'shopping-hero' => [
            'html' => function($tag) {

              $products =  $tag->parent()->products()->toStructure();

              return ' '. $products->subtitle() . ' ';

            }]
    ]
]);

Would appreciate the help if anyone has and idea/experience with this.
Thank you!

As I said, $products is now a collection with the items in your structure field. You have to loop through it, there is not subtitle on $products but only on the individual items.