How to make wp_insert_post_data and sessions work together properly?
I'm trying to process the post content before saving it to database and inform user if there was any error. I'm using wp_insert_post_data filter, sessions and admin_notices, since it seems to be the only simple solution to throw the error message to edit screen in admin panel after publishing. However, I ran into strange problem - the code seems to run twice, so when I have:
function notices(){
if(!empty($_SESSION['notices'])) print $_SESSION['notices'];
unset ($_SESSION['notices']);}
add_action( 'admin_notices', 'notices' );
add_filter('wp_insert_post_data', 'processdata', '99', 2);
function processdata($data) {
$processed_content = filterthis($data['post_content']);
if($processed_content!='error') {
$data['post_content'] = $processed_content;
$_SESSION['notices'] .= '<div class="updated"><p>Everything is ok</p></div>';
return $data;
} else {
$_SESSION['notices'] .= '<div class="error"><p>Something went wrong</p></div>开发者_JAVA百科';
return $data;}
I receive two messages. I've made some tests and it seems that first is for content that is to be saved in database and second for the "old" content (already saved). For example: if previous content was "wrong" and the one to be saved is "ok", the first message is "ok" and second "error" and so on. However, all messages are generated on the same time (so this is not some kind of caching problem, I suppose). What is even more strange for me, is that if I use this simple code:
add_filter ('wp_insert_post_data', 'filterthis', '99', 2);
function filterthis($data){
$date = date('H:i:s');
$_SESSION['my_admin_notices'] .= '<div class="updated"><p>This is a message from '.$date.'</p></div>';
$data['post_content'] .= $date;
return $data;
}
I get also two messages, but only one piece of timing data appended to post content - identical to the one delivered by the first message. So it seems like the code runs twice, but only for the first time it saves the content to database... I'm totally confused after seven hours of googling and reading Codex. Maybe the solution is trivial, but I'm not really a PHP programmer, just learning it for a while, so I would be very glad if someone here could help me.
I have also face the same problem when I made custom field validation before publish the post. Also when update the published post this filter gives strange behavior. so I have decide to go for client side validation.
Which is very simple DOM operation.
Please refer following link if you want to use client side validation.
http://greatindiaclub.oliwy.net/?p=1101
精彩评论