I need to abort the post saving process when the post content contains a specific string and then display a message to the user.
I found a method to display the message but didn’t find a way to refuse post saving.
So far here’s what i’ve done
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;
}
1 Answer
I’d hooked to ‘wp_insert_post_empty_content’ filter. See 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
}