How can I add a unique page identifier to the body tag of each page?

I can see how to add template name and url / handle as a class or id to the body tag, but I’d like to generate and add a unique page id to each page (such as WordPress does) so that even if the page or template name (or url handle) is changed, the selector I’ve used for that page still works.

Has anyone done this?

Thanks!

Hello @JohnBr ,

You can use this one


Regards

Guleria

Yes I tried this, but it didn’t produce any result for id on my site. Even if it did, a change of handle would break the selector.

Usually, handle does not change even if you change the title of the product/page/article, so there is no real need for this.

But you can also use id – this would not change even when handle is changed.

Something like (need to add more choices instead of … )

{% liquid
  case request.page_type
    when 'product':
      assign id = product.id
    when 'collection'
      assign id = collection.id
    when 'blog'
      assign id = blog.id
    when 'article'
      assign id = article.id
    when 'page'
      assign id = page.id
    ...
  endcase
%}
{% capture uniq_id -%}
  {{- request.page_type | split: "/" | last -}}
  {%- if template.suffix %}--{{ template.suffix }}{% endif -%}
  {%- if id %}--{{ id }}{% endif -%}
{%- endcapture %}

https://shopify.dev/docs/api/liquid/objects/request

https://shopify.dev/docs/api/liquid/objects/template

https://shopify.dev/docs/api/liquid/objects/product#product-id