|
<?php |
|
class AllowedHtml { |
|
private $allowed = array(); |
|
public $default = array(); |
|
function __construct( $allowed = array() ) { |
|
$this->default = $allowed; |
|
} |
|
function add_tag( string $tag, $attributes = array() ) { |
|
if ( isset( $this->allowed[ $tag ] ) ) { |
|
$attributes = array_merge( $this->allowed[ $tag ], $attributes ); |
|
} |
|
$this->allowed[ $tag ] = new AllowedHtml($attributes); |
|
} |
|
function add_tags( array $tags ) { |
|
foreach( $tags as $key => $value ) { |
|
if ( is_array( $value ) ) { |
|
$allowed[ $key ] = new AllowedHtml( $value ); |
|
} else { |
|
$allowed[ $value ] = new AllowedHtml(); |
|
} |
|
} |
|
} |
|
function __toArray():array { |
|
return array_merge( |
|
$this->default, $this->allowed |
|
); |
|
} |
|
} |
|
|
|
/** |
|
* @See The following (mostly) replicates a much longer example from: |
|
* https://wp-mix.com/wordpress-basic-allowed-html-wp_kses/ |
|
*/ |
|
$allowed_html = new AllowedHtml( [ 'id', 'class', 'title', 'style', 'data' ] ); |
|
$allowed_html->add_tags( [ 'abbr', 'b', 'code', 'strike', 'strong', 'em', 'i' ] ); |
|
$allowed_html->add_tags( [ 'div', 'span', 'p' ] ); |
|
$allowed_html->add_tags( [ 'dd', 'dl', 'dt', 'li', 'ol', 'ul' ] ); |
|
$allowed_html->add_tags( [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6' ] ); |
|
$allowed_html->add_tag( 'a', [ 'rel' => [], 'href' => array( '_blank', '_top' ) ] ); |
|
$allowed_html->add_tag( 'blockquote', [ 'cite' ] ); |
|
$allowed_html->add_tag( 'q', [ 'cite' ] ); |
|
$allowed_html->add_tag( 'del', [ 'datetime' ] ); |
|
$allowed_html->add_tag( 'img', [ 'alt', 'height', 'width', 'src' ] ); |
|
|
|
$clean_html = wp_kses( |
|
$_POST[ 'content' ] ?? null, |
|
$allowed_html |
|
); |