Using WordPress ‘post_comments_link’ PHP filter

The post_comments_link WordPress PHP filter allows you to modify the HTML-formatted post comments link.

Usage

add_filter('post_comments_link', 'your_custom_function', 10, 2);
function your_custom_function($formatted, $post) {
    // your custom code here
    return $formatted;
}

Parameters

  • $formatted (string): The HTML-formatted post comments link.
  • $post (int|WP_Post): The post ID or WP_Post object.

More information

See WordPress Developer Resources: post_comments_link

Examples

Add a custom CSS class to the post comments link.

add_filter('post_comments_link', 'add_custom_class_to_comments_link', 10, 2);
function add_custom_class_to_comments_link($formatted, $post) {
    $formatted = str_replace('class="comments-link"', 'class="comments-link custom-class"', $formatted);
    return $formatted;
}

Add a Font Awesome icon before the post comments link.

add_filter('post_comments_link', 'add_font_awesome_icon_to_comments_link', 10, 2);
function add_font_awesome_icon_to_comments_link($formatted, $post) {
    $icon = '<i class="fas fa-comments"></i> ';
    $formatted = $icon . $formatted;
    return $formatted;
}

Change the text displayed in the post comments link.

add_filter('post_comments_link', 'modify_comments_link_text', 10, 2);
function modify_comments_link_text($formatted, $post) {
    $formatted = preg_replace('/<a href=.*">(.*)<\/a>/', '<a href="$1">Join the discussion</a>', $formatted);
    return $formatted;
}

Wrap the post comments link in a custom div container.

add_filter('post_comments_link', 'wrap_comments_link_in_container', 10, 2);
function wrap_comments_link_in_container($formatted, $post) {
    $formatted = '<div class="comments-link-container">' . $formatted . '</div>';
    return $formatted;
}

Remove comments link for specific post categories

Do not display the post comments link for posts in specific categories.

add_filter('post_comments_link', 'remove_comments_link_for_specific_categories', 10, 2);
function remove_comments_link_for_specific_categories($formatted, $post) {
    $exclude_categories = array('news', 'updates');
    $post_categories = wp_get_post_categories($post->ID, array('fields' => 'slugs'));

    if (array_intersect($exclude_categories, $post_categories)) {
        return '';
    }

    return $formatted;
}