questions

How to add hashtags and cashtags with a link in the WP comments?

Rate this post

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">\1\2</a> ', $content);
    return $content;
}

The above code works perfectly 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">\1\2</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.

 

✔️Solution:

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">\1\2</a>', $comment->comment_content );
    }
    return $comments;
}

Leave a Reply

Your email address will not be published.

Back to top button