javascriptwordpressinternal-link

Add URL to specific word across entire website


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).


Solution

  • 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>