0

I am trying to change the permalink #comment-xy to #customname-xy. When i change the corefile comment-template.php on line 754 to

$link = $link . '#customname-' . $comment->comment_ID;

I achieve the desired result. But of course this is not elegant.

So, i tried to add a filter to my functions.php:

/*has no effect*/
function directcommentlink( $link  ) {
    global $post;
    $hash = '#customname';
    return get_permalink( $post->ID ) . $hash;
}
add_filter( 'get_comments_link', 'directcommentlink' );

But this filter has no effect. What is wrong with this filter? Thanks for your interest. theo

1 Answer 1

2

Modifications of the core code are not recommended.

Note that the core get_comments_link() function considers two cases of $hash:

$hash = get_comments_number( $post_id ) ? '#comments' : '#respond';

Also note the second input argument is $post_id.

Here's your modified example:

add_filter( 'get_comments_link', function( $link, $post_id )
{
    $hash = get_comments_number( $post_id ) ? '#mycomments' : '#myrespond';
    return get_permalink( $post_id ) . $hash;

}, 10, 2 );

or another approach might be a simple replacement:

add_filter( 'get_comments_link', function( $link, $post_id )
{
    return str_replace( 
        ['#comments', '#respond'], 
        ['#mycomments','#myrespond'], 
        $link 
    );

}, 10, 2 );

But it sounds like you want to modify the get_comment_link() according to your line number reference. Then you should consider the get_comment_link filter:

add_filter( 'get_comment_link', function( $link, \WP_Comment $comment )
{
    return str_replace( 
        '#comment-', 
        '#mycomment-', 
        $link 
    );

}, 10, 2 );
3
  • 1
    Hi, Thanks a lot for your quick response. Your third suggestion works fine. regards theo (sorry, my reputation is low, cannot vote)
    – timholz
    Commented Jul 26, 2016 at 10:45
  • By the way: Birkir Bjarnasson plays in Basel (my home). We had a lot of fun watching the Iceland football team this year.
    – timholz
    Commented Jul 26, 2016 at 11:03
  • Hehe that was quite an adventure ;-) I've enjoyed traveling in Switzerland hopefully I can do that again and even visit Basel ;-) @timholz
    – birgire
    Commented Jul 26, 2016 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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