Created
February 26, 2023 21:15
-
-
Save mstfydmr/46631f3636335c4d5b20bf84053e0d5c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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