add class to internal links in content

i want to add a class to all links inside of the_content, that point to other interal content, f.ex. other posts and pages. i want to do this automatically. dunno if the best practise would be, to look for content or try to hook into the tinymce editor.. and eather way around, i don’t know how..

this is what i have:

<a title="title" href="url" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener">text</a>

and i want it to be

<a title="title" href="url" rel="nofollow noreferrer noopener" rel="nofollow noreferrer noopener" class="class">text</a>

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

i didn’t want to use js, i wanted a php solution, plus i also manipulate all internal links into anchor links. in the end, you have to decide for yourself, what would be the best way for you, php or js.

this goes into functions.php inside the current theme folder.

add_filter('the_content', 'crawl_content');
function crawl_content( $text ) {
    $url = str_replace("/", "/", "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    $search = '/href="https?://' . $url . '(?:[^/" rel="nofollow noreferrer noopener"]+/)*([^/"]+)+/"/';
    preg_match_all( $search, $text, $matches);
    for ($a = 0; $a < count($matches[0]); $a++)    {
        $new = "href="#" . $matches[1][$a] . "" class="newsLink"";
        $text = preg_replace('%' . $matches[0][$a] . '%', $new, $text);
    }
    return $text;
}

internal links without the filter look like this:

<a title="title" href="http://example.com/some-random-subdings-or-not/post-slug/" rel="nofollow noreferrer noopener">Link Text</a>

with the filter it looks like this:

<a title="title" href="#post-slug" rel="nofollow noreferrer noopener" class="newsLink">Link Text</a>

external links will be left as they are.

Method 2

You can do this in jquery on document load. Using addClass

$("#DivName").find("a").addClass("YourClassHere");


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x