Skip to content

Fix canonical URL generation for first page in pagination #71

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Feb 17, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/MetaTags/Concerns/ManageLinksTags.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,12 @@ public function getCanonical(): ?TagInterface

public function setPaginationLinks(Paginator $paginator): self
{
$this->setCanonical($paginator->currentPage() > 1 ? $paginator->url($paginator->currentPage()) : $paginator->url(1));

$canonical = $paginator->url($paginator->currentPage());
if ($paginator->currentPage() == 1) {
$canonical = preg_replace('/[?&]page=\d+/', '', $canonical);
$canonical = rtrim($canonical, '?');
}
$this->setCanonical($canonical);
$this->setNextHref($paginator->nextPageUrl());
$this->setPrevHref($paginator->previousPageUrl());

Expand Down
2 changes: 1 addition & 1 deletion tests/MetaTags/PaginatorMetaTagsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ function test_its_can_be_set_from_paginator()
// Mock methods to simulate paginator behavior for the first page.
$paginator->shouldReceive('nextPageUrl')->once()->andReturn('http://site.com?page=2');
$paginator->shouldReceive('previousPageUrl')->once()->andReturn(null); // No previous page for the first page
$paginator->shouldReceive('currentPage')->once()->andReturn(1);
$paginator->shouldReceive('currentPage')->twice()->andReturn(1);
$paginator->shouldReceive('url')->with(1)->andReturn('http://site.com'); // Canonical URL without ?page=1
$paginator->shouldReceive('url')->with(2)->andReturn('http://site.com?page=2');

Expand Down
Loading