How to Safely Enable Shortcodes in WordPress Post Comments

This piece of code will allow any user with the capability of ‘moderate_comments’, to include a shortcode within a post comment. If the user does not have this permission, any shortcodes will be displayed as normal text. The code should be placed inside your theme’s functions.php file.

This is useful when combined with affiliate marketing plugins that allow you to display a clickable ad using a shortcode. A visitor to your site might post a comment on an article, requesting a recommendation for a product. You can then reply to their comment, and include a affiliate link or banner ad that advertises the product in question.

For example, you may post an article about Tennis, and a user may request a recommendation for a suitable tennis racket. You can then reply with a recommendation for a racket, with an advertisement for that racket that any user who reads that ad may decide to click.

function filterComments($comments)
{
$filtered_comments = array();
foreach ($comments as $comment)
{
// if not registered
if ($comment->user_id == 0)
{
$filtered_comments[] = $comment;
}
else
{
$comment_author = new WP_User($comment->user_id);
// if has capability 'moderate_comments'
if ($comment_author->has_cap('moderate_comments'))
{
$comment->comment_content = do_shortcode($comment->comment_content);
$filtered_comments[] = $comment;
}
else
{
$filtered_comments[] = $comment;
}
}
}
return $filtered_comments;
}

add_filter( 'comments_array', 'filterComments' );