0

I'm trying to implement a custom functionality to a wordpress shortcode plugin that shows a tooltip for specified words by automatically calling for information from Wikipedia.

Currently my code snippet works fine, but it shows the tooltips for each occurrence of the word in an article. For example if I specified the word : "dessert" in an array it will show the tooltip for all 5 words "dessert" found in the post. I'm looking for a way to limit the tooltip shortcode to be applied only once per word ( in this case "dessert" which has been specified in the array).

Me code snippet is this:

function add_wikitips($content) {
        if( is_single() && is_main_query() ) {
        $arr = array('dessert');
         for ($i = 0; $i < count($arr); $i++) {
          $content = str_replace($arr[$i], '[wiki]'.$arr[$i].'[/wiki]', $content);
         }
        }
      
     return $content;
}
    add_filter('the_content', 'add_wikitips'); 

I tried adding ob_end_clean(); then

static $content = null;
if ($content === null) {
return $content;
}

, but these methods didn't work. Probably because I didn't implement them properly.

Thanks a lot in advance for any advice and suggestions.

1 Answers1

0

Probably, you can try this: Using str_replace so that it only acts on the first match?

You want the first work to have Wiki link. So replace the first occurrence only when you are doing str_replace()

May be like:

function str_replace_first($from, $to, $content)
{
    $from = '/'.preg_quote($from, '/').'/';

    return preg_replace($from, $to, $content, 1);
}

echo str_replace_first('abc', '123', 'abcdef abcdef abcdef'); 
// outputs '123def abcdef abcdef'

Mentioned in Karim's amswer

Malav Vasita
  • 110
  • 11
  • Thanks, but doesn't seem to work. When I use preg_replace it gives me an error for unexpected value. – ginmenor Oct 08 '20 at 10:40