2

When I paste a table into the WordPress editor, I always get widths like <td width="232">.

I want to remove all widths when tables are added to the editor.

If it was regex, I would write something like: width="([0-9]+)".

How do I go about accomplishing this?

  • Working to get your question reopened since this is a relevant WordPress question. – MikeNGarrett May 7 at 18:03
1

I would approach this by modifying the attributes allowed in the table, tr, and td markup from wp_kses. wp_kses is a function that runs on the content to filter out unwanted tags and attributes. It stands for KSES Strips Evil Scripts, but it does much more than that.

It's a large and sometimes convoluted function, but it's very useful if you want to extend or modify what it filters out.

Keep in mind, this only applies to users without the unfiltered_html capability.

The wp_kses_allowed_html filter allows you to modify the allowed tags and attributes. The array structure is $allowedtags['tag_name']['attribute'], so you would look for $allowedtags['table']['width'], for example.

function my_modify_tags( $tags, $context ) {
    if ( 'post' !== $context ) {
        return $tags;
    }
    if ( isset( $tags['table']['width'] ) ) {
        unset( $tags['table']['width'] );
    }
    if ( isset( $tags['td']['width'] ) ) {
        unset( $tags['td']['width'] );
    }
    if ( isset( $tags['th']['width'] ) ) {
        unset( $tags['th']['width'] );
    }
    return $tags;
}
add_filter( 'wp_kses_allowed_html', 'my_modify_tags', 1, 2 );

The $context here allows for this to apply to specific instances where you want to modify the tags. By targeting post, you can have this filtered list of allowed tags only apply to the post content.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.