The get_comments_link WordPress PHP filter allows you to modify the post comments permalink.
Usage
add_filter('get_comments_link', 'your_custom_function', 10, 2); function your_custom_function($comments_link, $post) { // your custom code here return $comments_link; }
Parameters
$comments_link
(string) – The post comments permalink with ‘#comments’ appended.$post
(int|WP_Post) – The Post ID or WP_Post object.
More information
See WordPress Developer Resources: get_comments_link
Examples
Add a custom query parameter
Add a custom query parameter to the comments link.
add_filter('get_comments_link', 'add_custom_query_parameter', 10, 2); function add_custom_query_parameter($comments_link, $post) { $comments_link .= '&custom_param=value'; return $comments_link; }
Change the comments anchor
Change the anchor appended to the comments link.
add_filter('get_comments_link', 'change_comments_anchor', 10, 2); function change_comments_anchor($comments_link, $post) { $comments_link = str_replace('#comments', '#custom_anchor', $comments_link); return $comments_link; }
Add a tracking parameter
Add a tracking parameter to the comments link for analytics purposes.
add_filter('get_comments_link', 'add_tracking_parameter', 10, 2); function add_tracking_parameter($comments_link, $post) { $comments_link .= '&utm_source=comments'; return $comments_link; }
Append post ID to the anchor
Append the post ID to the comments anchor to create unique anchors for each post.
add_filter('get_comments_link', 'append_post_id_to_anchor', 10, 2); function append_post_id_to_anchor($comments_link, $post) { $post_id = is_object($post) ? $post->ID : $post; $comments_link = str_replace('#comments', '#comments_' . $post_id, $comments_link); return $comments_link; }
Modify comments link based on post type
Change the comments link depending on the post type.
add_filter('get_comments_link', 'modify_comments_link_based_on_post_type', 10, 2); function modify_comments_link_based_on_post_type($comments_link, $post) { if ($post->post_type === 'custom_post_type') { $comments_link = '/custom_comments_page/?post_id=' . $post->ID; } return $comments_link; }