当帖子内容包含特定字符串时,我需要中止帖子保存过程,然后向用户显示消息。
我找到了显示消息的方法,但没有找到拒绝保存帖子的方法。
到目前为止,我已经做到了
add_action( "pre_post_update", "checkPost");
function checkPost($post_ID) {
$post = get_post($post_ID);
$postContent = $post->post_content;
if ( wp_is_post_revision( $post_ID ) )
return;
if(preg_match("/bad string/", $postContent) == 1) {
//
// cancel post save
//
// then
add_filter("redirect_post_location", "my_redirect_post_location_filter", 99);
}
}
function my_redirect_post_location_filter($location) {
remove_filter(\'redirect_post_location\', __FUNCTION__, 99);
$location = add_query_arg(\'message\', 99, $location);
return $location;
}
add_filter(\'post_updated_messages\', \'my_post_updated_messages_filter\');
function my_post_updated_messages_filter($messages) {
$messages[\'post\'][99] = \'Publish not allowed\';
return $messages;
}
SO网友:david.binda
我已连接到“wp\\u insert\\u post\\u empty\\u content”过滤器。看见https://core.trac.wordpress.org/browser/tags/3.8.1/src/wp-includes/post.php#L2748
//hook at the very end of all filters to prevent other filters from overwriting your return value ( 99 should be high enaugh )
add_filter( \'wp_insert_post_empty_content\', \'my_cancel_post_save_function\', 99, 2 );
function my_cancel_post_save_function( $maybe_empty, $postarr ) {
if ( true === wp_is_post_revision( $postarr[ \'ID\' ] ) ) { //postarr is not an object, but array
return $maybe_empty; //do not forget to return original value to keep other filters working
}
if( true === preg_match("/bad string/", $postarr[ \'post_content\' ] ) ) {
return true; // triggers the post saving cancelation in wp_insert_post function
}
return $maybe_empty; //do not forget to return original value to keep other filters working
}