Remove Spaces from Advanced Custom Field if empty - php

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.

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;

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

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

Related

Sanitize and combine four ACF fields into one new ACF field

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

Replacing characters at start/end of string with PHP's ltrim/rtrim

I am looking to clean whitespace and hyphen characters from the start/end of a string.
I have the following test code:
$sample_titles = array(
'— — -Daisy Chain –',
'Ocarina for a Mermaid –',
' –—Another for a Sailor - '
);
foreach ( $sample_titles as $title ) {
$updated_title = ltrim( $title, ' -–—' );
$updated_title = rtrim( $updated_title, ' -–—' );
echo $updated_title . '<br/>';
}
This correctly outputs:
Daisy Chain
Ocarina for a Mermaid
Another for a Sailor
However, when I apply the same ltrim/rtrim logic in a foreach loop (over post titles, I'm "cleaning" imported data, the rest of the code is irrelevant) like this:
foreach ( $product_ids as $key => $product_id ) {
$title = get_the_title( $product_id );
$updated_title = ltrim( $title, ' -–—' );
$updated_title = rtrim( $updated_title, ' -–—' );
echo $updated_title . '<br/>';
};
I still end up with the hyphens/dashes/whitespace like this:
Orb 3 –
Ocarina for a Mermaid –
Mini Marina –
Any ideas why this works in one context but not the other?
Simply wrapping the title grab function in html_entity_decode() fixed the issue I was having:
$product_title = html_entity_decode( get_the_title( $product_id ) );

Wordpress taxonomy last child separated by "en" instead of comma

I'm trying to create a shortcode that outputs my custom taxonomies, separated by a comma, but i want the last comma to be "en" instead of a comma. So like this:
taxonomy, taxonomy, taxonomy en taxonomy
So far i have this:
// Assortiment shortcode
function verlichting_type( ){
$terms = get_the_terms( $post->ID, 'verlichting_type' );
foreach($terms as $term) {
$entry_terms .= $term->name . ', ';
}
$entry_terms = rtrim( $entry_terms, ', ' );
return '<span class="verlichting__type"> ' . $entry_terms . ' </span>';
}
add_shortcode( 'verlichting_type', 'verlichting_type' );
WordPress already have custom printf function with localize the output
So if your site language is Francais means
wp_sprintf_l( '%l', ['Hello', 'world', 'never', 'give', 'up'] )
The above code will output
Hello, world, never, give, et up
For Espanol:
Hello, world, never, give y up
As you noted based on the language the last comma will be added/removed
As I dont have an example of the $terms or $entry_terms variable I had to make up some dummy data, but I think you should be able to extract my example and place it into your code.
I made use of the ternary operator (https://www.php.net/manual/en/language.operators.comparison.php) to determine whether or not the final comma should be ',' or 'en':
<?php
function verlichting_type() {
$entry_terms = "";
$terms = [
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy'],
(object)['name' => 'taxonomy']
];
echo '<span class="verlichting__type">';
foreach ( $terms as $index => $term) {
$enIndex = sizeof($terms) - 2;
$end = (isset($terms[$enIndex]) && $index == $enIndex ? ' en ' : ', ');
$entry_terms .= $term->name . $end;
}
$entry_terms = rtrim( $entry_terms, ', ' );
return $entry_terms . '</span>';
}
This outputs:
<span class="verlichting__type">taxonomy, taxonomy, taxonomy en taxonomy</span>
This should work with any array length, e.g. if $terms only has 2 elements:
<span class="verlichting__type">taxonomy en taxonomy</span>
Or 1 element:
<span class="verlichting__type">taxonomy</span>

" ' " being converted into " ‘ "

add_filter( 'comment_text', 'mh_commenttaglink' , 50 );
function mh_commenttaglink( $text ) {
// RegEx to find #tag, #hyphen-tag with letters and numbers
$mh_regex = "/\#[a-zA-Z0-9-]+/";
// Use that RegEx and populate the hits into an array
preg_match_all( $mh_regex , $text , $mh_matches );
// If there's any hits then loop though those and replace those hits with a link
for ( $mh_count = 0; $mh_count < count( $mh_matches[0] ); $mh_count++ )
{
$mh_old = $mh_matches[0][$mh_count];
$mh_old_lesshash = str_replace( '#' , ' ' , $mh_old );
$mh_new = str_replace( $mh_old , '' . $mh_old . '' , $mh_matches[0][$mh_count] );
$text = str_replace( $mh_old , $mh_new , $text );
}
// Return any substitutions
return $text;
}
I have a small custom plugin for wordpress here that converts all hashtagged terms in post comments into searchable links.
I know this plugin is causing the issue as it only buggers off after deactivation, I just cant see where in this code I need to edit something out or add somethign in to prevent it.
More experienced eyes would be appreciated.

PHP over trim! Text disappearing! But why?

I just want to display the categories for my blog posts, but to SOME of the categories (and especially if they stand alone, the last bit get's trimmed away ~ "Music" becomes "Mu", and "Adventure" becomes "Adventur" ... any help? Please!
// Category boxes :P
function showcatz() {
global $post;
echo '<div class="categz_wrapper"><div class="categz">';
// get the category IDs assigned to post
$categories = wp_get_post_categories( $post->ID, array( 'fields' => 'ids' ) );
// separator between links
$separator = '</div><div class="categz"> ';
if ( $categories ) {
// List categories
$cat_ids = implode( ',' , $categories );
// Remove ONE category from the list
$kill = array("411,", "411");
$killit = str_replace($kill, "", $cat_ids);
$cats = wp_list_categories( 'title_li=&style=none&echo=0&include=' . $killit);
$cats = rtrim( trim( str_replace( '<br />', $separator, $cats ) ), $separator );
// Only show categories if there is any
if ( $killit ) { echo $cats; }
}
echo '</div></div>';
}
your passing a parameter to rtrim called $separator which has the value </div><div class="categz"> so when the following statement is executed it will remove the following chars from your string. div<>clastegz
rtrim( str_replace( '<br />', $separator, $cats ) ), $separator );
Solution, remove the second parameter to rtrim

Categories