In a recent project, we had to implement functionality where the page title changes according to values submitted in the form. Since the page titles in our website was handled using meta tags, the challenge was that even when the form was submitted, the title of the page remained the same with only the query parameters changing.
In this post, I will show you how to add different titles for a page with the same URL.
In our case, we were checking the value in the query string parameter and setting the page title. You can use hook_tokens_alter() to update the page title token. An example of the hook_tokens_alter() implementation is given below:
/** * Implements hook_tokens_alter(). */ function MODULE_NAME_tokens_alter(&$replacements, $context) { if ($context['type'] == 'current-page') { if (isset($context['tokens']['title'])) { if (isset($_GET['category'])) { // Do custom processing $replacements['[current-page:title]'] = t('Custom page title'); } } } }
This helped us change the title per page request but the meta tag module caches page titles by checking the page URL. This means that only one page title will be cached for one URL. So we had to implement hook_metatag_page_cache_cid_parts_alter() to set the cid for setting page title cache. An example of the hook_metatag_page_cache_cid_parts_alter() implementation is given below:
/** * Implements hook_metatag_page_cache_cid_parts_alter(). */ function MODULE_NAME_metatag_page_cache_cid_parts_alter(&$cid_parts) { if (arg(0) == 'category') { $cid_parts['path'] = substr(request_uri(), '1'); } }
This way, request_uri will be set as the cid for caching the page title. This helps us set our own cid whenever the parameter is dynamic on the page.