WordPress- Cancel post saving process

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.

Read More

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;
 }

Related posts

Leave a Reply

1 comment

  1. Hope this helps you to check post content

    function to_err_is_human( $post_id ) {
        // If this is just a revision, don't check
        if ( wp_is_post_revision( $post_id ) )
            return;
        $post_content = wp_unslash(!empty($_REQUEST['content']) ? $_REQUEST['content'] : $post_data['content']);
            if ($post_content=="abc")
            { add_filter("redirect_post_location", "my_redirect_post_location_filter", 99);}
    }
    add_action( 'save_post', 'to_err_is_human' );
    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;
     }