虽然Andre的回答部分正确,但仅限于Javascript函数,链接教程也没有提供完整的答案。这是一个完整的解决方案,包括正面和背面:
add_action(\'admin_footer-post.php\',\'my_pre_post_update_hook\');
add_action(\'admin_footer-post-new.php\',\'my_pre_post_update_hook\');
function my_pre_post_update_hook(){
global $post;
?>
<script type="text/javascript">
jQuery(document).ready(function() {
// We listen to Ajax calls made via fetch
var temp_fetch = window.fetch;
window.fetch = function() {
return new Promise((resolve, reject) => {
temp_fetch.apply(this, arguments)
.then((response) => {
if( response.url.indexOf("/wp-json/wp/v2/posts") > -1 &&
response.type === \'basic\'
){
var clone = response.clone();
clone.json().then(function (json) {
if( typeof json.code !== \'undefined\' &&
typeof json.code === \'string\' &&
typeof json.message !== \'undefined\' &&
typeof json.message === \'string\'
){
wp.data.dispatch("core/notices").createNotice(
json.code,
json.message,
{
// type: "snackbar", // Optional
id: \'custom_post_site_save\',
isDismissible: true
}
);
// Close default "Post saved" notice
wp.data.dispatch( \'core/notices\' ).removeNotice(\'SAVE_POST_NOTICE_ID\');
// You can see all active notices by this command:
// wp.data.select(\'core/notices\').getNotices();
}
});
}
resolve(response);
})
.catch((error) => {
reject(error);
})
});
};
// If you want to listen to Ajax calls made via jQuery
// jQuery(document).bind("ajaxSend", function(event, request, settings){
// }).bind("ajaxComplete", function(event, request, settings){
// });
});
</script>
<?php
}
add_action( \'pre_post_update\', \'custom_post_site_save\', 10, 2);
function custom_post_site_save($post_id, $post_data) {
if (wp_is_post_revision($post_id)) { // If this is just a revision, don\'t do anything.
return;
} elseif (isset($post_data[\'post_content\']) && strpos($post_data[\'post_content\'], \'myTextString\') !== false) {
$code = \'error\'; // Can be one of: success, info, warning, error.
$response_body = \'My custom message ...\';
$error = new WP_Error($code, $response_body);
wp_die($error, 200);
}
}