您可以使用该功能get_posts
获取所有帖子,然后使用foreach循环,使用您发布的regex替换img标记,然后使用wp_update_post
更改帖子内容:
function remove_images_form_past_posts() {
if ( get_transient(\'images_removed_from_past\') ) return;
$posts = get_posts(\'nopaging=1\');
if ( $posts ) {
foreach ( $posts as $post ) {
$newcontent = preg_replace(\'/<img[^>]+\\>/i\', \'\', $post->post_content);
$newpost = array( \'ID\' => $post->ID, \'post_content\' => $newcontent);
wp_update_post($newpost);
}
set_transient(\'images_removed_from_past\', 1);
}
}
add_action(\'admin_init\',\'remove_images_form_past_posts\');
此代码只能使用一次,以更改过去的帖子内容。为了确保它只运行一次,我使用了瞬态。参见法典
Transient API.
现在您必须添加一个钩住\'wp_insert_post_data\'
过滤器挂钩和防止新帖子添加图像:
function remove_images_before_publish( $data, $postarr ) {
if ( ! empty($data[\'post_content\']) )
$data[\'post_content\'] = preg_replace(\'/<img[^>]+\\>/i\', \'\', $data[\'post_content\']);
return $data;
}
add_filter(\'wp_insert_post_data\',\'remove_images_before_publish\', 20, 2);