Difference between revisions of "User:Ilmari Karonen/canonical"

From NetHackWiki
Jump to navigation Jump to search
(Quick and dirty MediaWiki hook to add rel=canonical links to all normal page view)
 
(rewrite for MediaWiki 1.24)
 
Line 4: Line 4:
 
$wgHooks['ArticleViewHeader'][] = 'addCanonicalLinks';
 
$wgHooks['ArticleViewHeader'][] = 'addCanonicalLinks';
 
function addCanonicalLinks ( &$article ) {
 
function addCanonicalLinks ( &$article ) {
        global $wgRequest, $wgOut;
+
if ( $article->getOldID() ) return true; // permalink to old version or diff
        if ( $article->getOldID() || $wgRequest->getVal( 'redirect' ) == 'no' ) return true;
+
if ( $article->getPage()->getID() == 0 ) return true; // redlink, shared image, etc.
        $tags = ( $wgOut->mLinktags ? $wgOut->mLinktags : array() );
+
 
        foreach ( $tags as $tag ) {
+
$context = $article->getContext();
                if ( $tag['rel'] === 'canonical' ) return true;
+
if ( $context->getRequest()->getVal( 'redirect' ) == 'no' ) return true; // redirect
        }
+
 
        $wgOut->addLink( array( 'rel' => 'canonical',
+
// XXX: MediaWiki core only calls setCanonicalUrl() for shared images and redirects,
        'href' => $article->getTitle()->getFullURL() ) );
+
// and for the latter case it sets the exact same canonical URL as we set here.
        return true;
+
$context->getOutput()->setCanonicalUrl( $article->getTitle()->getLocalURL() );
 +
return true;
 
}</source>
 
}</source>

Latest revision as of 22:17, 27 November 2014

Quick and dirty MediaWiki hook to add rel=canonical links to all normal page views:

$wgHooks['ArticleViewHeader'][] = 'addCanonicalLinks';
function addCanonicalLinks ( &$article ) {
	if ( $article->getOldID() ) return true;  // permalink to old version or diff
	if ( $article->getPage()->getID() == 0 ) return true;  // redlink, shared image, etc.

	$context = $article->getContext();
	if ( $context->getRequest()->getVal( 'redirect' ) == 'no' ) return true;  // redirect

	// XXX: MediaWiki core only calls setCanonicalUrl() for shared images and redirects,
	// and for the latter case it sets the exact same canonical URL as we set here.
	$context->getOutput()->setCanonicalUrl( $article->getTitle()->getLocalURL() );
	return true;
}