Select Page

Do you want to allow your users to use shortcodes in their comments? There’s an easy way to do this.

Warning: Allowing shortcodes in your WordPress comments can be a security hazard. Don’t use the below code unless you know what you’re doing.

Place this code in your theme’s functions.php file or create a custom plugin with this code:

/**
 * Custom function to add shortcode support to WordPress comments
 *
 * @param string $comment The comment text
 *
 * @return string $comment The modified comment text with shortcode support
 */
function add_shortcode_support_to_comments( $comment ) {
  // Enable shortcode support in comments
  $comment = do_shortcode( $comment );
  return $comment;
}
add_filter( 'comment_text', 'add_shortcode_support_to_comments', 10, 1 );

The ‘add_shortcode_support_to_comments’ function is a custom function that takes one argument: $comment. The $comment argument is the comment text.

Inside the function, the ‘do_shortcode’ function is used to process shortcodes in the comment text. This enables shortcode support in comments. Finally, the function is hooked to the ‘comment_text’ filter using the ‘add_filter’ function, which applies the changes to the comment text.

This code will add shortcode support to WordPress comments on your site. You can use this code to enable shortcodes in comments and customize the appearance and behavior of your comments using shortcodes. Please note that you should use caution when enabling shortcode support in comments, as it can create security vulnerabilities if used improperly.

A better approach would be only to allow a set of whitelisted shortcodes in the comments.

This code only allows certain whitelisted shortcodes in the comment content:

/**
 * Custom function to add shortcode support to WordPress comments and only allow certain shortcodes from a whitelist array
 *
 * @param string $comment The comment text
 *
 * @return string $comment The modified comment text with shortcode support
 */
function add_shortcode_support_to_comments( $comment ) {
  // Set up a whitelist of allowed shortcodes
  $shortcode_whitelist = array( 'shortcode1', 'shortcode2', 'shortcode3' );

  // Process shortcodes in the comment text, but only allow shortcodes from the whitelist
  $comment = do_shortcode( $comment, $shortcode_whitelist );
  return $comment;
}
add_filter( 'comment_text', 'add_shortcode_support_to_comments', 10, 1 );

In this improved version of our function, a whitelist of allowed shortcodes is defined in the $shortcode_whitelist array. The ‘do_shortcode’ function is then used to process shortcodes in the comment text, but only shortcodes from the whitelist are allowed. This enables shortcode support in comments, but only for shortcodes from the whitelist.