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">text</a>

and i want it to be

<a title="title" href="url" class="class">text</a>

2 Answers 2


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 . '(?:[^\/"]+\/)*([^\/"]+)+\/"/';
    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.


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

  • hi and thanks for the help. but nope. this would catch ALL links, but i only want the internal ones. guess php is the only way..
    – honk31
    Jul 29, 2014 at 15:28
  • you can use filter to check what the href value is. See here
    – jbyrne2007
    Jul 29, 2014 at 15:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.