Currently my theme calls upon get_comments_link() to create the standard anchor #comments to link to the comments below the post, as does the get_comments_pagenum_link() function on paginated comments.

I would like to replace the #comments anchor in these functions with any other string, without of course changing WP's core php files.

A simple add_filter to completely replace core functions (other than in pluggable.php) doesn't seem to be possible. Are there any other ways of achieving this small change to the output of a core function, that use PHP (rather than say Java)? Is there a way here of using an add_filter with str_replace() perhaps?

This will be useful for foreign language sites, and for redirecting comments to another page with a url request, for example.


So the solution to the get_comments_pagenum_link() function is straightforward enough:

add_filter('get_comments_pagenum_link' , 'new_get_comments_pagenum_link');
function new_get_comments_pagenum_link($content) {
    $content = str_ireplace('#comments' , '#other', $content);
    return $content;

Which filters the output of get_comments_pagenum_link() to replace #content with #other, or any other string you might choose.

For the get_comments_link() function, which can't be filtered, I have simply discovered that my WordPress theme uses it already within its own comments link function, and so have filtered this theme function instead, using the same method shown above.


For the function get_comments_link() no such filter exists. You might want to use an alternative function called get_comment_link() which has a filter: get_comment_link.

For the function get_comments_pagenum_link() a filter exists: get_comments_pagenum_link.

To learn about how filters work please see Plugin API (Wordpress Codex). The information there should answer all question about how to use add_filter().

As the link is a string in PHP, you can use any of the PHP string functions to locate, extract and replace stuff. Full list of PHP String functions (PHP Manual).


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.