对于我当前的一个项目,我不得不将博文从旧的 WordPress 站点转移到我的项目中。
事情进展顺利,直到我看到所有的帖子都是从 Word 中复制粘贴的,几乎每个段落之前都留下了这个:
<span style="font-size: medium; font-family: georgia,palatino;">
在某些地方,像这样的事情:
<p style="text-align: justify;">
<p style="text-align: justify;"><span style="font-size: medium; font-family: georgia,palatino;"><strong><span style="color: #000000;">
因此,因为我没有 40 小时(甚至更少的耐心)来进入每个帖子(大约 100 个)并删除那些不需要的标签,所以我正在寻找一个过滤器,它可以删除所有样式(除非可能它在输出 the_content() 之前包含 text-decoration:underline) 元素
有这样的事吗?
如果我们想去除所有的内联样式,那么只需要在functions.php中添加如下代码即可。
add_filter('the_content', function( $content ){
//--Remove all inline styles--
$content = preg_replace('/ style=("|\')(.*?)("|\')/','',$content);
return $content;
}, 20);
只需将其添加到您的 functions.php。
Note: This filter works at the time of saving/updating the post.
add_filter( 'wp_insert_post_data' , 'filter_post_data' , '99', 2 ); function filter_post_data( $data , $postarr ) { $content = $data['post_content']; $content = preg_replace('#<p.*?>(.*?)</p>#i', '<p>\1</p>', $content); $content = preg_replace('#<span.*?>(.*?)</span>#i', '<span>\1</span>', $content); $content = preg_replace('#<ol.*?>(.*?)</ol>#i', '<ol>\1</ol>', $content); $content = preg_replace('#<ul.*?>(.*?)</ul>#i', '<ul>\1</ul>', $content); $content = preg_replace('#<li.*?>(.*?)</li>#i', '<li>\1</li>', $content); $data['post_content'] = $content; return $data; }
Note: This filter works at the time when function the_content() is executed.
add_filter( 'the_content', 'the_content_filter', 20 ); function the_content_filter( $content ) { $content = preg_replace('#<p.*?>(.*?)</p>#i', '<p>\1</p>', $content); $content = preg_replace('#<span.*?>(.*?)</span>#i', '<span>\1</span>', $content); $content = preg_replace('#<ol.*?>(.*?)</ol>#i', '<ol>\1</ol>', $content); $content = preg_replace('#<ul.*?>(.*?)</ul>#i', '<ul>\1</ul>', $content); $content = preg_replace('#<li.*?>(.*?)</li>#i', '<li>\1</li>', $content); return $content; }