4

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;
 }
  • I had a similar issue before, where i wanted to prevent the user to save a post until a certain field that needed to be filled with the correct information. In my case I used jquery to disable the save button and only enable it if the field had the value I was looking for. With jquery you could also easily display a error message. – gdaniel Jan 30 '14 at 22:13
1

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
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.