Overriding Page Title in a Contextual View

Submitted by Tom Thorp on Tuesday, September 25, 2018 - 16:04
Modified on Friday, July 5, 2019 - 21:56
Drupal 8
(Note: At time of writing, I was using Drupal 8.6.1 with Metatag 8.x-1.7 . Metatag as yet had not incorporated access to the view content.)


Using Views within Drupal 8 presents some unusual problems to the developer, particularly when contextual filters come into play. Such is the case when you try to include the argument value as part of your Page Title, in order to distinguish individual pages for SEO purposes. 
In short, you can't. By default Views can only go so far as to change the contents of the view's title page (by selecting 'Override Title' via the Contextual Filter). However, there is a work-around for this issue.


Within your custom module, add the following : 

 * Implements hook_views_post_render().
 * Note that this is targeted at a specific viewid + pageid combination,
 *    and could be further optimized if more than one is required. 
function MODULE_NAME_views_post_render($view) {
  if ($view->id() !== 'ViewMachineId' && $view->getDisplay()->getPluginId() !== 'PageMachineId') {

  $request = \Drupal::request();

  if ($route = $request->attributes->get(\Symfony\Cmf\Component\Routing\RouteObjectInterface::ROUTE_OBJECT)) {
    $new_title = $view->getTitle();
    $route->setDefault('_title', $new_title);
By implenting this function call into your custom module, you will not only have your Page Title change according to which argument value is passed - you will also keep Google happy with individualised search engine results. 

About the author

Tom Thorp
Tom Thorp is an IT Consultant living in Miami on Queensland's Gold Coast. With over 30+ years working in the IT industry, Tom's experience is a broad canvas. The IT services Tom provides to his clients, includes :
Website development and hosting
Database Administration
Server Administration (Windows, Linux, Apple)
PABX Hosting and Administration
Helpdesk Support (end-user & technical).
  If you like any of my content, consider a donation via Crypto by clicking on one of the payment methods :
DrupalViewsSEOPage Title