web-dev-qa-db-fra.com

Annuler la sauvegarde

J'ai besoin d'abandonner le processus de post-enregistrement lorsque le contenu du post contient une chaîne spécifique, puis d'afficher un message à l'utilisateur.

J'ai trouvé une méthode pour afficher le message mais je n'ai pas trouvé le moyen de refuser l'enregistrement après.

Jusqu'ici voici ce que j'ai fait

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

J'avais accroché au filtre 'wp_insert_post_empty_content'. Voir 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
}
1
david.binda