使用act/ save_post在保存时删除高级自定义字段数据中的空格


Remove Spaces from Advanced Custom Field data on Save using act/ save_post

我试图从数据中自动删除空格,当自定义帖子更新或保存在wordpress中时,ACF插件生成的自定义字段中输入数据。

我相信我需要使用acf/save_post钩子,但我正在努力让preg_replace工作。我想知道我是否没有使用正确的标识符,因为自定义字段名称具有字段名称邮政编码,但检查时它具有名称字段[field_55c7969262970]。这个似乎也行不通。

function remove_spaces( $post_id ) {
if( empty($_POST['postcodes']) ) {       
    return;   
} else{
$postcodes = $_POST['postcodes'];   
$postcodes = preg_replace('/'s+/', '', $postcodes);
return $postcodes;  }      
}
add_action('acf/save_post', 'remove_spaces', 1);

我认为你最好使用acf/update_value过滤器。这个钩子允许你在一个字段被保存到数据库之前修改它的值。

function remove_spaces($value, $post_id, $field) {
    if(empty($value)) {       
        return;   
    }
    $value = preg_replace('/'s+/', '', $value);
    return $value;
}
add_filter('acf/update_value/name=postcodes', 'remove_spaces', 10, 3);