The following snippets will allow you to add html tags that are not allowed by default in WordPress Core. We hook into pre_comment_on_post
that runs just before a comment is saved to your database.
Here’s two version of snippets. The first allows one tag to be inserted, the second merges an array of tags you wish to bulk add to the $allowedtags
global variable.
Each tag as to be set as the key
of the array. The value of that key is another array. You set an empty array if you don’t want or need to add attributes for that tag. Again, each attributes is an array and the value is true to enable that specific attribute for that specific tag. The form is 'attribute' => true,
.
On to the examples so it’s more clear. Remember that there are security/spam reasons why tags have been restricted in the comments, so be wise about which tags you allow.
Add One Tag
To add one tag to the $allowedtags
array use this next snippet. Here we allow the img
tag with src
and alt
attributes
add_action('pre_comment_on_post', 'add_post_comment_html_tags' );
function add_post_comment_html_tags( $commentdata ) {
global $allowedtags;
$allowedtags['img'] = [
'src'=> true,
'alt'=> true
];
}
Bulk Add Tags
To add multiple tags use this version. Here we add the img
tag with the src
and alt
attributes and the pre
tag
add_action('pre_comment_on_post', 'add_post_comment_html_tags' );
function add_post_comment_html_tags( $commentdata ) {
global $allowedtags;
$new_tags = [
'img'=> [
'src'=> true,
'alt'=> true
],
'pre'=> []
];
$allowedtags = array_merge( $allowedtags, $new_tags );
}
Remove a Tag From The Allowed List
To remove a tag you wish to restrict from the comments, just use unset()
to get the job done. Here’s how to prevent people from posting links in comments. The anchor text will still be shown but the actual link will be stripped from the comment before it’s saved to the database.
add_action('pre_comment_on_post', 'add_post_comment_html_tags' );
function add_post_comment_html_tags( $commentdata ) {
global $allowedtags;
unset( $allowedtags['a'] );
}
List of Defaults Tags Allowed
If you want a list of tag allowed by WordPress Core, then here it is. So if it’s not in this list, it’s not allowed by default. Use the snippets above to include more tags.
a
taghref
attributetitle
attribute
abbr
tagtitle
attribute
acronym
tagtitle
attribute
b
tagblockquote
tagcite
attribute
cite
tagcode
tagdel
tagdatetime
attribute
em
tagi
tagq
tagcite
attribute
s
tagstrike
tagstrong
tag
Bruce Deniger says
This is quite useful. Thank you for this valuable information.
Vishal Kakadiya says
This is great, thank you so much.