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

Topic summary

A Shopify theme developer seeks to add a unique, persistent page identifier to the body tag that won’t break when page names or URL handles change—similar to WordPress’s page ID system.

Initial Attempts:

  • Tried using page.handle as suggested, but it produced no results and would still break if the handle changed.

Recommended Solution:

  • Use Shopify’s built-in object IDs (e.g., product.id, page.id, collection.id) which remain constant even when handles or titles change.
  • Implementation involves Liquid code that:
    • Detects the page type using request.page_type
    • Assigns the appropriate ID based on the object type
    • Combines page type, template suffix, and ID into a unique identifier

Key Insight:

  • Handles typically don’t change when titles are updated, making this less critical than initially thought.
  • However, using object IDs provides the most reliable, persistent identifier across all page types.
Summarized with AI on October 28. AI used: claude-sonnet-4-5-20250929.

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

1 Like

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

1 Like