最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Remove all table widths from editor content

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited May 7, 2019 at 19:23 MikeNGarrett 2,6711 gold badge20 silver badges29 bronze badges asked May 7, 2019 at 16:06 KrystleKrystle 232 bronze badges 1
  • Working to get your question reopened since this is a relevant WordPress question. – MikeNGarrett Commented May 7, 2019 at 18:03
Add a comment  | 

1 Answer 1

Reset to default 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.

发布评论

评论列表(0)

  1. 暂无评论