add class to internal links in content

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("https://wordpress.stackexchange.com/", "\/", "$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]");
    $search="/href="https://wordpress.stackexchange.com/questions/156186/https?:\/\/" . $url . '(?:[^\/"]+\/)*([^\/"]+)+\/"https://wordpress.stackexchange.com/";
    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/">Link Text</a>

with the filter it looks like this:

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

external links will be left as they are.

Leave a Comment