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 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">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.
2
Answers
Try the below code. the "$comments" parameter is an array object of WP_Comment Object so you have access by loop.
I do not WP, but judging my Bhautik’s answer, you are dealing with an array of objects. Because objects remain mutable in a loop, you can apply the change directly to the object without referring to it by its key.
Your regex pattern could do with some refinement. When matching a literal
$
and#
, just put them in a character class and avoid the piping and escaping.The
w+
is appropriate, but the following negated character class is not necessary. In fact, it will cause your pattern to fail if the very last character in the string are still thew
of the hash/cash substring.The
s
pattern modifier is only of any value if you have a non-literal.
in your pattern. You do not, so there is no use to the pattern modifier — omit it.Code: (Demo)