0

The goal is to replace words throughout the articles in a (WordPress) site. I have tried the code below, and it works, but I want to be able to limit it's effect. I want to only replace the first instance of a word on each post (currently it replaces all instances of course). The main purpose is to create sitewide links.

function link_words( $text ) {
    $replace = array(
        'google' => '<a href="http://www.google.com">Google</a>',
        'computer' => '<a href="http://www.myreferral.com">computer</a>',
        'keyboard' => '<a href="http://www.myreferral.com/keyboard">keyboard</a>'
    );
    $text = str_replace( array_keys($replace), $replace, $text );
    return $text;
}
add_filter( 'the_content', 'link_words' );
add_filter( 'the_excerpt', 'link_words' );

(Code credit to Ivan Juristic at First Site Guide https://firstsiteguide.com/search-and-replace-wordpress-text/)

EDIT: As Stackers already noted below, there is a problem where this code could inadvertently edit links and break them. Also, I did find that this code breaks links to pictures that have the word in them. So I'm also wondering how to only apply this to words in the paragraphs of the posts, not to other html.

1 Answers1

0

You might want to have a look at a combination of strpos() and substr_replace(). First, get the position of the first occurance in the post via strpos(), then replace this occurence with substr_replace():

function link_words( $text ) {
    $replace = array(
        'google' => '<a href="http://www.google.com">Google</a>',
        'computer' => '<a href="http://www.myreferral.com">computer</a>',
        'keyboard' => '<a href="http://www.myreferral.com/keyboard">keyboard</a>'
    );
    foreach ($replace as $key => $singleReplacement) {
        $start = strpos($text, $key);
        if ($start !== false) {
            $text = substr_replace($key, $singleReplacement,$start, strlen($key));
        }
    }
    return $text;
}
Tobias F.
  • 1,050
  • 1
  • 11
  • 23