WP-Mix

A fresh mix of code snippets and tutorials

Customize WordPress Allowed Tags for Comments

By default, the WordPress comment form enables users to include basic HTML tags in their comments. This includes tags like <p>, <br>, <strong>, and so forth. These basic tags suffice to add basic formatting in most cases. But for some setups, more tags may be needed.

For example, at my site Perishable Press, users discuss and share Apache/.htaccess code via comments. But with the limited HTML tags allowed by WordPress, anytime a user tries to share a comment that includes Apache tags, like <IfModule>, <Directory>, or <VirtualHost>, they are removed by WordPress comment filter system. This is true for any non-allowed tags, whether HTML or otherwise.

So to resolve this limitation, fortunately WordPress provides an easy way to customize the allowed tags for comments. For example, at Perishable Press (Yes theme), I add the following function:

function shapeSpace_add_allowed_tags() {
	
	global $allowedtags;
	
	$allowedtags['p']   = array('class' => true, 'id' => true);
	$allowedtags['ul']  = array('class' => true, 'id' => true);
	$allowedtags['ol']  = array('class' => true, 'id' => true);
	$allowedtags['li']  = array('class' => true, 'id' => true);
	$allowedtags['pre'] = array('class' => true, 'id' => true);
	
	$allowedtags['a']      = array('class' => true, 'id' => true, 'title' => true, 'data-url' => true, 'data-date' => true, 'data-title' => true, 'href' => true);
	$allowedtags['span']   = array('class' => true, 'id' => true, 'title' => true, 'data-url' => true, 'data-date' => true, 'data-title' => true);
	$allowedtags['strong'] = array('class' => true, 'id' => true, 'title' => true, 'data-url' => true, 'data-date' => true, 'data-title' => true);
	
	$allowedtags['ifmodule']    = array('class' => true, 'mod_rewrite.c' => true, 'mod_alias.c' => true, 'mod_auth.c' => true);
	$allowedtags['directory']   = array();
	$allowedtags['virtualhost'] = array();
	
	$allowedtags['info']   = array();
	$allowedtags['note']   = array();
	$allowedtags['update'] = array();
	
}
add_action('init', 'shapeSpace_add_allowed_tags', 11);

In addition to the default allowed basic HTML tags, this code adds some custom attributes that I use for expired/404 links. It also adds the aforementioned Apache tags, and a few miscellaneous tags that are used internally for record-keeping and so forth.

To use this code, add it to your theme functions file or add via custom plugin. And of course, customize the allowed tags/attributes as needed. Cheers!

Learn more

Digging Into WordPressWordPress Themes In DepthWizard’s SQL Recipes for WordPress