Adding hashtags and cashtags with a link in the WordPress comments

Ok, so I have managed to make it work for the_content, by adding this line in functions.php:

add_filter('the_content', 'my_hashcash_class');
function my_hashcash_class($content)
{
  
    $content = preg_replace('/($|#)(w+)[^w".;]/s', '<a href="https://www.mywebsite.com/?s=2">12</a> ', $content);
return $content;
}

The above code works perfect with the WordPress filter the_content

But when I’m trying to do the same for comments with the_comments, I’m getting an error:

There has been a critical error on this website.

Learn more about debugging in WordPress.

Comments are not even displayed.

Here’s my comments code:

add_filter('the_comments', 'my_hashcash_comments_class');
function my_hashcash_comments_class($comments)
{
  
    $comments = preg_replace('/($|#)(w+)[^w".;]/s', '<a href="https://www.mywebsite.com/?s=2">12</a> ', $comments);
return $comments;
}

Maybe wordpress is trying to apply the filter for commenter user name, avatar and all that other stuff.

I want the filter to be applied only to the comment content itself.

Any help would be appreciated.

thanks.

Answer

Try the below code. the “$comments” parameter is an array object of WP_Comment Object so you have access by loop.

add_filter('the_comments', 'my_hashcash_comments_class');
function my_hashcash_comments_class($comments){
    foreach ( $comments  as $key => $comment ) {
        $comments[$key]->comment_content = preg_replace( '/($|#)(w+)[^w".;]/s', '<a href="https://www.mywebsite.com/?s=2">12</a>', $comment->comment_content );
    }
    return $comments;
}

Leave a Reply

Your email address will not be published. Required fields are marked *