skip to Main Content

I need to sanitize the output of admin_notices which uses certain things like

  • a
  • id
  • href
  • title
  • strong

Is it good idea to use wp_kses_post function?

Reading docs I am uncertain what HTML tags are allowed https://developer.wordpress.org/reference/functions/wp_kses_post/

2

Answers


  1. To check the list of allowed tags and attributes for wp_kses_post you can use

    echo '<pre>';
    print_r( wp_kses_allowed_html( 'post' ) );
    echo '</pre>';
    die();
    

    In your case, where only a and strong allowed, you can use wp_kses function (docs) instead

    $allowed_html = [
        'a' => [
            'id' => true,
            'href'  => true,
            'title' => true,
        ],
        'strong' => [],
    ]; 
    $clear_post = wp_kses( $post, $allowed_html );
    
    Login or Signup to reply.
  2. wp_kses_post allows all HTML that is permitted in post content. So it will load a large array which is redundant in your case. As you need only some specific HTML tags to be sanitized, you should use the wp_kses function as you have control here and you can mention which HTML tags should be allowed. You can do as follows-

    $allowed_tags = [
        'a' => [
            'id'    => true,
            'href'  => true,
            'title' => true,
        ],
        'strong' => [],
    ]; 
    $sanitized_post = wp_kses( $post, $allowed_tags );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search