您可以使用the_content
(Click here for more info) 钩子在呈现帖子/页面时更改内容。
从数据库读取Post时将触发此操作。所以post内容不会在数据库中更改,只会在渲染时过滤。
add_filter( \'the_content\', \'remove_email_and_url_from_post\' );
function remove_email_and_url_from_post( $content ) {
// Check if we\'re inside the main loop in a single post page.
if ( is_single() && in_the_loop() && is_main_query() ) {
// For emails
$pattern = "/[^@\\s]*@[^@\\s]*\\.[^@\\s]*/";
$replacement = "[removed]";
$content = preg_replace($pattern, $replacement, $content);
// For urls
$pattern = "/[a-zA-Z]*[:\\/\\/]*[A-Za-z0-9\\-_]+\\.+[A-Za-z0-9\\.\\/%&=\\?\\-_]+/i";
$replacement = "[removed]";
$content = preg_replace($pattern, $replacement, $content);
}
return $content;
}
或者用同样的方法
content_save_pre
钩
这将在post保存到数据库时触发。因此,这实际上将从帖子中删除过滤后的内容,然后将其保存到数据库中。
function remove_email_and_url_from_post( $content ) {
return $content;
$pattern = "/[^@\\s]*@[^@\\s]*\\.[^@\\s]*/";
$replacement = "[removed]";
$content = preg_replace($pattern, $replacement, $content);
// For urls
$pattern = "/[a-zA-Z]*[:\\/\\/]*[A-Za-z0-9\\-_]+\\.+[A-Za-z0-9\\.\\/%&=\\?\\-_]+/i";
$replacement = "[removed]";
$content = preg_replace($pattern, $replacement, $content);
return $content;
}
add_filter( \'content_save_pre\', \'remove_email_and_url_from_post\', 10, 1 );