简体   繁体   English

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

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

I'm trying to remove spaces automatically from data entered into a custom field generated by the ACF plugin when a custom post is updated or saved in wordpress. 我正在尝试在自定义帖子被更新或保存在wordpress中时自动从输入到由ACF插件生成的自定义字段中的数据中删除空格。

I believe I need to use the acf/save_post hook but I'm struggling to get the preg_replace to work. 我相信我需要使用acf / save_post钩子,但是我在努力使preg_replace起作用。 I wonder if I'm not using the right identifier as the custom field name has field name postcodes but when inspected it has name fields[field_55c7969262970]. 我想知道我是否没有使用正确的标识符,因为自定义字段名称具有字段名称邮政编码,但是在检查时却具有名称字段[field_55c7969262970]。 Can't seem to make it work with that either. 似乎也无法使其正常工作。

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);

I think you are better off using the acf/update_value filter. 我认为您最好使用acf/update_value过滤器。 From thr docs: "This hook allows you to modify the value of a field before it is saved to the database." 来自thr docs:“此挂钩可让您在将字段的值保存到数据库之前对其进行修改。”

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM