简体   繁体   中英

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

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]);

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM