Add URL to specific word across entire website

145 Views Asked by At

I want to be able to link any word of my choice to a specific URL for example: I want the word "goat" to link to "http://goat.com" across the entire website. So all "goat"/s will link to that URL right across the website.

I am using wordpress and I have not yet found a plugin to do this. If I can get a solution to this I would most likely create a plugin for this functionality.

I know how to target one word on a single page. But I would like it to be across all the pages and all the words in those pages( I used JavaScript for this).

3

There are 3 best solutions below

2
On BEST ANSWER

Here's a crappy solution but it's better than nothing:

I found some code here which searches for a world across the whole page so I copy pasted that and modified it.

The replaceWord variable cannot contain the same string as word, otherwise it'll loop infinitely.

var word = " goat",
    replaceWord = " <a href = 'http://goat.com'>goat</a>",
    queue = [document.body],
    curr
;
while (curr = queue.pop()) {
    if (!curr.textContent.match(word)) continue;
    for (var i = 0; i < curr.childNodes.length; ++i) {
        switch (curr.childNodes[i].nodeType) {
            case Node.TEXT_NODE : // 3
                if (curr.childNodes[i].textContent.match(word)) {
                    curr.innerHTML = curr.innerHTML.replace(word,replaceWord);
                }
                break;
            case Node.ELEMENT_NODE : // 1
                queue.push(curr.childNodes[i]);
                break;
        }
    }
}
Hello goat

<div>Look a goat</div>

0
On

This might be a bit resource intensive and replaceWord cannot contain the same string as word, otherwise it'll loop forever.

document.onload = function() {
    var word = " goat",
        replaceWord = " <a href = 'http://goat.com'>goat</a>";

    while(document.body.innerHTML.indexOf(word) !== -1) {
        document.body.innerHTML = document.body.innerHTML.replace(word,replaceWord);
    }
}
Hello goat

<div>Look a goat</div>

2
On

Something like this may work for you.

function replaceWithUri(textToReplace, element){
    element.innerHTML = element.innerHTML.replace(textToReplace, '<a href="http://www.' + textToReplace + '.com" >' + textToReplace + '</a>');
}

replaceWithUri('goat', document.getElementsByTagName('body')[0]);