Add Snippet To Project
Engaging with your visitors through comments is a great way to foster a community on your website. But what if you want to highlight a specific comment or direct someone’s attention to a particular part of the comment thread? One solution is to use comment hashes and jQuery to create a link that jumps straight to the desired comment and highlights it. In this article, we’ll take a look at how you can implement this feature on your WordPress site.
function wpturbo_highlight_comments() {
?>
<!-- Add this style in your css file or inside style tag -->
<style>
.highlight {
background-color: #FFFFCC;
padding: 0.5rem;
}
</style>
<!-- Add this script in the header.php file -->
<script>
jQuery(document).ready(function($){
// Get the hash from the URL
var commentHash = window.location.hash;
// If it starts with "#comment-" strip off "#comment-" to get the comment ID.
if ( commentHash.indexOf("#comment-") === 0 ){
var commentID = commentHash.substr(9);
// Remove the previous highlight class if it exists.
$('.highlight').removeClass('highlight');
// Add the highlight class to the comment.
$('#comment-' + commentID).addClass('highlight');
}
});
</script>
<?php
}
add_action( 'wp_head', 'wpturbo_highlight_comments' );
This article will explain how to use comment hash and jQuery to highlight comments on a WordPress site. The code snippet provided above is the complete solution for this problem.
The first step required is to define a new function wpturbo_highlight_comments()
that we will use to highlight comments on the WordPress site. Inside this function, we include the required CSS and JavaScript code that will help us achieve our goal.
First, we add the CSS style that will highlight the comment. We define the class .highlight
to have a yellow background color with a slight padding to separate the comment. You could customize this CSS class to match your desired style.
Then, we add the JavaScript code inside a script tag. Using jQuery, we wait for the document to be fully loaded. Then, we retrieve the hash from the URL using window.location.hash
.
If the hash starts with the string #comment-
, it means the user has clicked on a specific comment, and we can read the comment ID. So, we store the trimmed comment ID in a variable called commentID
.
Next, we remove the previous .highlight
class from the previously highlighted comment if it exists. Finally, we add the 'highlight' class to the current comment by targeting it with $('#comment-' + commentID)
.
Lastly, we use the add_action()
function to add the wpturbo_highlight_comments()
function to the wp_head
action in the WordPress theme. This ensures that our highlighting script runs on every page load.
In conclusion, the code snippet provided above is a straightforward solution for highlighting comments on your WordPress site using jQuery and comment hash.