wp_kses_post only removes <script> tags, but not their content

Is there any way to remove the script tags including their contents?

wp_kses_post seems to only remove the tags, while their content remains visible on the page.

Thank you

Topic wp-kses Wordpress

Category Web


Yes, use this function: (from https://www.php.net/manual/en/function.strip-tags.php#86964)

function strip_tags_content($text, $tags = '', $invert = FALSE) {

  preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
  $tags = array_unique($tags[1]);
   
  if(is_array($tags) AND count($tags) > 0) {
    if($invert == FALSE) {
      return preg_replace('@<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>@si', '', $text);
    }
    else {
      return preg_replace('@<('. implode('|', $tags) .')\b.*?>.*?</\1>@si', '', $text);
    }
  }
  elseif($invert == FALSE) {
    return preg_replace('@<(\w+)\b.*?>.*?</\1>@si', '', $text);
  }
  return $text;
}

& after that, if you also want to remove all attributes except few(example: href, title), use wp_kses like this:

    $content = wp_kses($content, array(
        'a' => array('href' => true, 'title' => true),
        'div' => array(),
        'p' => array(),
    ));

I suggest You to use preg_replace() to filter the post content:

add_filter('the_content', 'my_strip_scripts');

function my_strip_scripts($content){

    return preg_replace('#<script(.*?)>(.*?)</script>#is', '', $content);

}

This is what I use on my site to strip images and paragraph tags. I'm assuming this is the_content?

<?php
ob_start();
the_content();
$old_content = ob_get_clean();
$new_content = strip_tags($old_content, '<insert HTML tags you want kept');
echo $new_content; ?>

The $new_content line will remove all HTML tags except those tags listed after $old_content


KSES is designed to prevent execution of undesired and potentially dangerous tags, not preventing display of the innerHTML. Blocking the content would require

--1 Either a custom function that used some kind of string manipulation or xmlDOM manipulation to remove content; or

--2 A function that blocked posts that contain the tag with a message why the post failed and instructions for using HTML codes to render script tag when using it in tutorials rather than as an execution tag.

Number 1 may produce performance issues with its higher overhead. If optimizing performance is an issue or if the site involves heavy posting by multiple users, then #2 is likely a more feasible solution.


Give wp_strip_all_tags() a shot. I believe it removes the content of script tags also.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.