Change all website links to affiliate links automatically

雨燕双飞 提交于 2019-12-01 00:18:42

Right way is to use LinkerMakeExternalLink mediawiki hook like that ( you can put it at bottom of your LocalSettings.php:

$wgHooks['LinkerMakeExternalLink'][] = 'ExampleExtension::exampleLinkerMakeExternalLink';

class ExampleExtension {
    public static function exampleLinkerMakeExternalLink( &$url, &$text, &$link, &$attribs, $linktype ) {
        if( strpos( $url, 'gog.com') !== false ) {
            $url .= '?pp=708a77db476d737e54b8bf4663fc79b346d696d2';
        }
        return false;
    }
}

Not sure how great it would be performance wise for hundreds of links.

// Plain Javascript

var links = document.getElementsByTagName('a');

for (var i = 0, max = links.length; i < max; i++) {
    var _href = links[i].href;

    if (_href.indexOf('gog.com') !== -1) {
        links[i].href = _href + '?pp=708a77db476d737e54b8bf4663fc79b346d696d2';   
    }
}

DEMO

So you can also use jquery to bind any link click. This way you can do your link eval on the fly. This jsfiddle is a rough run through of what i think you're trying to accomplish. The alerts are just for your benefit and should be removed.

$("a").click(function() {
    addAffiliate(this);
});

myCode = "?pp=708a77db476d737e54b8bf4663fc79b346d696d2";
myAmazonCode = "?tag=shihac-20"
    function addAffiliate(link) {
        alert("enterting script: " + link.href);
        if ((link.href).indexOf("gog.com") > -1 && (link.href).indexOf(myCode) < 0) {
                link.href = link.href + myCode;
        }else if((link.href).indexOf("amazon.com") > -1 && (link.href).indexOf(myAmazonCode) < 0){
                link.href = link.href + myAmazonCode;   
        }
            alert(link.href);
            return true;
        }​

http://jsfiddle.net/du47b/23/

UPDATE: added code and fully qualified paths

UPDATE: added 'else if' block for other codes. using 'else if' instead of just another if block will hopefully cut back on unnecessary processing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!