nystudio107 / craft-seomatic

SEOmatic facilitates modern SEO best practices & implementation for Craft CMS 3. It is a turnkey SEO system that is comprehensive, powerful, and flexible.
https://nystudio107.com/plugins/seomatic
Other
166 stars 71 forks source link

Unable to add jsonLd items to itemListElement using "key" #1533

Closed tibbis closed 1 week ago

tibbis commented 1 week ago

Question

I'm struggling to create a ItemList with products inside a itemListElement array JsonLd object using the key feature in a for loop. Only the last item is correctly added to the itemListElement, the rest as separate ItemLists. What am I doing wrong?

I could of course create an array by merging them and then adding it to seomatic.jsonld but prefer to avoid doing that.

{% for plan in plans.all() %}

{% set itemListJsonLd = seomatic.jsonLd.get("ItemList") %}

{% if itemListJsonLd.itemListElement is not defined %}
    {% set itemListJsonLd = seomatic.jsonLd.create({
        "type": "ItemList",
        "itemListElement": []
    }, true) %}

{% endif %}

{% set listItem = seomatic.jsonLd.create({
    "key": "plan-" ~ plan.slug,
    "type": "ListItem",
    "position": loop.index,
    "item": {
        "type": "Product",
        "name": plan.title,
        "review": {
            "type": "Review",
            "reviewRating": {
                "type": "Rating",
                "ratingValue": plan.planRating|default(5),
            },
        }
    }
}, true) %}
{% do itemListJsonLd.itemListElement(listItem) %}
{% endfor %}

Resulting in:

Screenshot 2024-11-04 at 15 52 09

Additional context

Craft CMS Pro v5.4.9 + Seomatic plugin.

amabilee commented 1 week ago

This might be because of how the key feature is implemented in your loop. Have you tried using the append method to ensure each listItem is correctly added to the itemListElement array without overwriting the previous items?

khalwat commented 1 week ago

yep what @amabilee said is likely what is happening here.

khalwat commented 1 week ago

Also check out some samples here that add a list of things:

https://nystudio107.com/blog/annotated-json-ld-structured-data-examples

tibbis commented 1 week ago

This might be because of how the key feature is implemented in your loop. Have you tried using the append method to ensure each listItem is correctly added to the itemListElement array without overwriting the previous items?

I tried{% do itemListJsonLd.append(listItem) %} but "append" method does not exist in this context.

I managed to get it working by adding a static key to the ItemList and then:

{% set updatedItemList = itemListJsonLd.getAttributes().itemListElement | merge([listItem]) %}
{% do itemListJsonLd.setAttributes({
    "itemListElement": updatedItemList
}, false) %}