I'm combining four individual ACF fields into one text field, but I need to sanitize those entries individually so I can use them all as CSS classes. I've been trying to use sanitize_title() to turn plain english field values into the equivalent of post slugs—lowercase with dashes instead of spaces and no special characters.
A simplified, two-field example would be:
Status One / Status Two
and Sector One / Sector Two / Sector Three
into
status-one-status-two sector-one-sector-two-sector-three
Note that I'm trying to sanitize before merging so I can keep my entries separated by spaces (i.e. multiple CSS classes instead of one-incredibly-long-css-class.
I found the original function here and successfully modified it to merge four of my fields into a fifth ACF field.
function my_acf_save_post( $post_id ) {
$value1 = get_field( 'status', $post_id );
$value2 = get_field( 'sector', $post_id );
$value3 = get_field( 'subsector', $post_id );
$value4 = get_field( 'lead', $post_id );
$clean1 = sanitize_title( $value1 );
$clean2 = sanitize_title( $value2 );
$clean3 = sanitize_title( $value3 );
$clean4 = sanitize_title( $value4 );
$merge = implode(" ",$clean1).' '.implode(" ",$clean2).' '.implode(" ",$clean3).' '.implode(" ",$clean4);
update_field( 'css_classes', $merge );
}
add_action('acf/save_post', 'my_acf_save_post', 20);
I've tried a number of sanitize_*
functions—most of them at this point—and a kajillion different syntaxes and I still can't get it to work because I'm a designer who writes a bit of code and not a developer (but you know that by now). kthxbai in advance.
Try out this code to create a slug and merge fields into one.
function custom_slug($text, string $divider = '-')
{
// replace non letter or digits by divider
$text = preg_replace('~[^\pL\d]+~u', $divider, $text);
// transliterate
$text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
// remove unwanted characters
$text = preg_replace('~[^-\w]+~', '', $text);
// trim
$text = trim($text, $divider);
// remove duplicate divider
$text = preg_replace('~-+~', $divider, $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return 'n-a';
}
return $text;
}
function my_acf_save_post( $post_id ) {
$value1 = get_field( 'status', $post_id );
$value2 = get_field( 'sector', $post_id );
$value3 = get_field( 'subsector', $post_id );
$value4 = get_field( 'lead', $post_id );
$clean1 = custom_slug( $value1 );
$clean2 = custom_slug( $value2 );
$clean3 = custom_slug( $value3 );
$clean4 = custom_slug( $value4 );
$merge = $clean1.' '.$clean2.' '.$clean3.' '.$clean4;
update_field( 'css_classes', $merge, $post_id );
}
add_action('acf/save_post', 'my_acf_save_post', 20);