I'm trying to perform some checks on custom fields before they are saved on a db. So I decided to use an add_filter as it does this between browser and db. Here is my code
function fields_pre_check($post_id){
$errors = false;
$values = get_post_custom(get_the_ID());
$act_val = $_POST['checks_news'];
...altri checks...
if(get_check_key($post_id, $act_val , $values)){
$errors = true;
update_option('custom_token', $errors);
update_option('custom_admin_errors', $txt_err=error_text($errors, 2));
remove_action('save_post','update_fields');
wp_update_post(array('ID' => get_the_ID(), 'post_status' => 'draft'));
add_action('save_post', 'update_fields');
return false;
}
}
function update_fields($post_id){
$chk1 = $_POST['checks_news'];
update_post_meta($post_id, 'checks_news', $chk1);
}
function get_check_key($post, $checker, $val){
global $wpdb;
$wpdb->query("SELECT meta_value, meta_key
FROM $wpdb->wp_postmeta
WHERE meta_value = $checker");
if(get_post(get_the_ID())==NULL){
return ($wpdb->num_rows != 0);
}
else{
if($val['checks_news'][0] == $checker)
return false;
else{
return ($wpdb->num_rows != 0);
}
}
}
add_filter('wp_insert_post_data', 'fields_pre_check');
add_action('save_post', 'update_fields');
I choose add_filter because the function get_check_key has to verify the previous value $val['checks_news'][0] with the new one $checker( if I use add_action, which i tried, they are the same because $val['checks_news'][0] retrieves the value just saved so if wanna change that value from 1 to 2 and perform the check it returns 2 == 2). The problem comes when I want to use $wpdb->num_rows which returns always 0 even if the result should be 1. What am i doing wrong? Did I take the right way using add_filter instead of add_action?