I'm using a custom comment_type for my plugin and that comment type is connected to only a custom post_type. And now I want to add the TinyMCE Editor to the comment section, and want to allow more tags than typical, especially some headings, pre tag, and ordered & unordered lists. But adding an editor to the comment section is the half part of it. I need to allow those tags to bypass the wp_kses for the comment content.
I did something earlier, that seems foolish now:
$response_msg = wp_kses( $response_msg, my_allowed_html() );
$comment_id = wp_new_comment( array(
'comment_post_ID' => absint( $post->ID ) ,
'comment_author' => wp_strip_all_tags( $current_user->display_name ),
'comment_author_email' => sanitize_email( $current_user->user_email ),
'comment_author_url' => esc_url( $current_user->user_url ),
'comment_content' => $response_msg,
'comment_type' => 'wpse_response',
'comment_parent' => 0,
'user_id' => absint( $current_user->ID ),
) );
Because even though the my_allowed_html()
function passes newly allowed HTML to the comment section, the wp_new_comment()
, with its inherited filter will wp_kses()
all of 'em to the defaults. So that's foolish.
I figured out that this solution is not a good one, as of now (WP v5.2.1) comment_post
would be too late to hook for this. The correct code for doing this would be what Milan Petrovic suggested:
function wpse20190615_allowed_html_in_responses($comment_content)
{
global $allowedtags;
$allowedtags['pre'] = array('class'=>array());
$allowedtags['h2'] = array();
$allowedtags['h3'] = array();
$allowedtags['h4'] = array();
$allowedtags['h5'] = array();
$allowedtags['h6'] = array();
$allowedtags['ul'] = array();
$allowedtags['ol'] = array();
$allowedtags['li'] = array();
return $comment_content;
}
add_filter( 'pre_comment_content', 'wpse20190615_allowed_html_in_responses', 9 );
But what I understand is, this filter will allow these HTML tags into all the comments, including the default comments for posts, pages. I want to allow these HTML tags restricted to only the comments of my comment_type (or my post type).
I tried with the init
hook but seems global $post
and $post->post_type
detection might be too earlier, so eventually not worthy for my case.
And pre_comment_content
allows only a single parameter and that doesn't have the information about the comment type also.
So, how can I restrict the code above to a certain comment_type, something like:
function wpse20190615_allowed_html_in_responses($comment_content)
{
// if('wpse_response' !== $comment->comment_type) {
// return $comment_content;
// }
global $allowedtags;
...
return $comment_content;
}
add_filter( 'pre_comment_content', 'wpse20190615_allowed_html_in_responses', 9 );