Problem/Motivation
Same rel="canonical"
for view pages with and without exposed filters.
Steps to reproduce
I have a view Cities
with not required exposed filter country
.
Case 1:
I left this filter empty all cities in all countries are shown.
<link rel="canonical" href="https://xn----7sblvlgns.xn--p1ai/cities" />
All is OK.
Case 2:
I select country Norway and all cities in all Norway are shown.
But canonical
is still same.
But this is completely different page.
Should be <link rel="canonical" href="https://xn----7sblvlgns.xn--p1ai/cities?country=no" />
As a result this page was deleted from search engine ranking.
Proposed resolution
Add selected (not all) exposed filter values to rel="canonical"
Remaining tasks
User interface changes
API changes
Data model changes
Release notes snippet
As a workaround:
/**
* Implements hook_page_attachments_alter().
*/
function my_module_page_attachments_alter(array &$attachments) {
$route_name = \Drupal::routeMatch()->getRouteName();
if ($route_name == 'view.cities.page') {
$request = \Drupal::request();
if ($request->query->has('country')) {
$country_id = $request->query->get('country');
$url = Url::fromRoute($route_name, [],
[
'query' => ['country' => $country_id],
])->setAbsolute();
$attachments['#attached']['html_head']['canonical_url'] = [
[
'#tag' => 'link',
'#attributes' => [
'rel' => 'canonical',
'href' => $url->toString(),
],
],
'canonical_url',
];
}
}
}