Reputation: 3
Trying to remove the whitespace before the , if the $middle field is empty. This is the code I have
function show_update_postdata( $value, $post_id, $field ) {
// Get values from POST
$first = $_POST['acf']['field_5b8536ef3839f'];
$middle = $_POST['acf']['field_5b853701383a0'];
$last = $_POST['acf']['field_5b8536e53839e'];
$creds= $_POST['acf']['field_5b853717383a1'];
// Custom post title
$title = $last . ', ' . $first . ' '. $middle .', ' . $creds;
$slug = sanitize_title( $title );
$postdata = array(
'ID' => $post_id,
'post_title' => $title,
'post_type' => 'physicians',
'post_name' => $slug
);
wp_update_post( $postdata );
return $value;
}
add_filter('acf/update_value/name=first_name', 'show_update_postdata', 10, 3);
add_filter('acf/update_value/name=middle_name_initial', 'show_update_postdata', 10, 3);
add_filter('acf/update_value/name=last_name', 'show_update_postdata', 10, 3);
add_filter('acf/update_value/name=credentials', 'show_update_postdata', 10, 3);
Currently the output is Doe, John D., MD if the $middle has a value, but if the $middle has no value I am getting this Doe, John , MD but it should be Doe, John, MD
Any help would be much appreciated.
Upvotes: 0
Views: 1407
Reputation: 325
Use rtrim function instead of trim to validate every single variable and url.
$var=rtrim($variable);
$var=ltrim($var);
otherwise empty() check is the best solution
if(empty($variable))
Upvotes: 1
Reputation:
You can use trim()
function to...
Strip whitespace (or other characters) from the beginning and end of a string
if(empty($middle)) $middle = trim($middle);
Upvotes: 1
Reputation: 3431
but if the $middle has no value I am getting this Doe, John , MD
Just because $middle is empty, the space character inserted before it does not automatically disappear with it.
So check if the variable is empty, and only if not, insert the space and the value:
$title = $last . ', ' . $first . ( $middle != '' ? ' '.$middle : '' ) .', ' . $creds;
Upvotes: 2