1
votes

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);
1
what does the $post_id parameter of the function do? Could that possibly be function remove_spaces( $post_id ) { if( empty($_POST[$post_id]) ) { return; } else{ $postcodes = $_POST[$post_id]; $postcodes = preg_replace('/\s+/', '', $postcodes); return $postcodes; } } - Professor Abronsius

1 Answers

2
votes

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