Show favicon only for a first link from that host

I wrote a simple wordpress plugin that shows a favicon next to a link in a wordpress page/post content.

add_filter( ‘the_content’, ‘favicon_content_filter’, 20 );

Read More
/**
 * Add a icon to the beginning of every post page.
 */
function favicon_content_filter( $content ) {
    $content = preg_replace('/<a href="(.+)">/', '<img src="http://www.google.com/s2/favicons?domain=$1" /> <a href="$1">', $content);
    return $content;
}

Now, the client wants to have this favicon displayed next to a link ONLY for the first time when that particular link shows up on a page.

I’m stuck with this for a few hours already. Obviously, I’m not that good with regex. Any help would be highly appreciated

Related posts

Leave a Reply

1 comment

  1. You can use strpos function:

    /**
     * Add a icon to the beginning of every post page.
     */
    function favicon_content_filter( $content ) {
        if (strpos($content, "http://www.google.com/s2/favicons") === false) {
           $content = preg_replace('~<a href="([^"]+)">~', '<img src="http://www.google.com/s2/favicons?domain=$1" /> <a href="$1">', $content);
        }
        return $content;
    }
    

    This will replace $content only if /s2/favicons isn’t there in it already.