简体   繁体   中英

Add a class attribute to certain links

I have pages on my site that go through a translation proxy. I need the displayed text in certain links to not be translated. I can add class="notranslate" to the link and the translator will skip over it no problem. However, I have hundreds of pages created before I implemented the translator and I'll have hundreds more as I keep going along—manually adding the class is not really an option.

The links I'm specifically concerned with are ones whose display text are literal URLs or email addresses. The translator doesn't touch the href attributes so the links still work as expected, but the displayed string gets mangled. For instance, in Vietnamese, "organization@domain.com" is displayed as "tổ chức@domain.com," and a link whose display text should be "domain.com/committees" is translated to "domain.com/commitaries."

So I'm looking for a solution that finds a elements whose display text contains "@" or "/" and adds class="notranslate" . I don't think I need too robust a solution as I otherwise don't use the "@" or "/" in link display text often, if ever, except in these situations. I would guess this could be done with Javascript, but I'm a JS beginner at best. An option that filters content on the backend through Wordpress could also be a nice solution.

This is simple using jquery, ideally this will need to load before your translations plugin.

Note: If you have jquery already loaded as most wordpress themes already do, then you can remove the first line from this code, which includes the jquery library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
  $( document ).ready(function() {
    $("a").each(function() {
    
      let text = $(this).text();  
    
      if(text.includes("@")) {
        $(this).addClass('notranslate');
      }

      if(text.includes("/")) {
        $(this).addClass('notranslate');
      }
 
    })
});
</script>

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