WordPress:如何在wp_insert_post_data中显示自定义错误消息

问题描述

|| 我将显示一个自定义-错误消息。
function ccl($data,$postarr = \'\') {
 if($data[\'post_status\'] == \"publish\"){
  $data[\'post_status\'] = \"draft\"; 
  echo \'<div id=\"my-custom-error\" class=\"error fade\"><p>Publish not allowed</p></div>\';
 }  
  return $data;
}

add_filter( \'wp_insert_post_data\',\'ccl\',\'99\' );
我已经尝试了很多想法,但是每当文章发布的wordpress发出成功消息时,都会出现。我可以取消成功消息并显示自己的错误消息吗? 坦克求救...     

解决方法

        您无法在
wp_insert_post_data
过滤器中打印错误,因为此后用户将立即被重定向。最好的办法是进入重定向过滤器,并在查询字符串中添加消息变量(这将覆盖任何现有的Wordpress消息)。 因此,在您的
wp_insert_post_data
过滤器函数中添加重定向过滤器。
add_filter(\'wp_insert_post_data\',\'ccl\',99);
function ccl($data) {
  if ($data[\'post_type\'] !== \'revision\' && $data[\'post_status\'] == \'publish\') {
    $data[\'post_status\'] = \'draft\';
    add_filter(\'redirect_post_location\',\'my_redirect_post_location_filter\',99);
  }
  return $data;
}
然后在重定向过滤器函数中添加一个消息变量。
function my_redirect_post_location_filter($location) {
  remove_filter(\'redirect_post_location\',__FUNCTION__,99);
  $location = add_query_arg(\'message\',99,$location);
  return $location;
}
最后,钩入“ 5”过滤器并添加您的消息,以便Wordpress知道要打印的内容。
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;
}