简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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