Skip to content

Instantly share code, notes, and snippets.

@mstfydmr
Created February 26, 2023 21:15
Show Gist options
  • Save mstfydmr/46631f3636335c4d5b20bf84053e0d5c to your computer and use it in GitHub Desktop.
Save mstfydmr/46631f3636335c4d5b20bf84053e0d5c to your computer and use it in GitHub Desktop.
<?php
function addCanonicalTag($html, $url) {
$dom = new DOMDocument();
@$dom->loadHTML($html, LIBXML_HTML_NODEFDTD);
$head = $dom->getElementsByTagName('head')->item(0);
if ($head) {
$canonical = $dom->getElementsByTagName('link')->item(0);
if ($canonical) {
$canonical->setAttribute('href', $url);
} else {
$newCanonical = $dom->createElement('link');
$newCanonical->setAttribute('rel', 'canonical');
$newCanonical->setAttribute('href', $url);
$head->appendChild($newCanonical);
}
}
return $dom->saveHTML();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment