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.

I believe I need to use the acf/save_post hook but I’m struggling to get the preg_replace to work. 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]. 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);

Related posts

1 comment

  1. I think you are better off using the acf/update_value filter. From thr docs: “This hook allows you to modify the value of a field before it is saved to the database.”

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

Comments are closed.