This is a PHP function that takes the contents of a text area field in WordPress and performs several operations to tidy up the data. The function:
- Explodes the text area content into separate lines using the “\n” line break character.
- Trims white space from each line using the
array_map
function with thetrim
function. - Removes any blank lines and duplicates using the
array_unique
andarray_filter
functions. - Sorts the lines in alphabetical order using the
sort
function. - Joins the lines back together into a single string using the
implode
function and the PHP_EOL line break character.
Finally, the function is added as a filter to the ACF (Advanced Custom Fields) update value process for the text_list
field. This means that every time the text_list
field is updated, the tidy_textarea_lines
function will be executed to process the text area contents.
text_list name of your ACF Text Area field. ACF New Lines set to Automatically add paragraphs.
/** | |
* Take the contents of a text area, de-dupe, remove blanks and sort. | |
* | |
* @param string $string Text area content. | |
* | |
* @return string | |
*/ | |
function tidy_textarea_lines( $string ) { | |
$source_lines = explode( “\n”, str_replace( “\r”, ”, $string ) ); | |
$source_lines = array_map( ‘trim’, $source_lines ); // Trim white space from lines. | |
$source_lines = array_unique( array_filter( $source_lines ) ); // Remove blanks & duplicates. | |
sort( $source_lines ); | |
return implode( PHP_EOL, $source_lines ); | |
} | |
add_filter( ‘acf/update_value/name=text_list‘, ‘tidy_textarea_lines’, 10, 1 ); |