I am at the moment doing shortcodes for ACF, and wanted to know if there is a way of shortening it, instead of re-creating the same shortcode again and again, only to change the $value.
Here is the code:
function acf_shortcode_distance( $atts ) {
// extract attributs
extract( shortcode_atts( array(
'field' => '',
'post_id' => false,
'format_value' => true
), $atts ) );
// get value and return it
$value = get_field( $field, $post_id, $format_value );
if (empty($value)) {
return '';
}
// array
if( is_array($value) ) {
$value = @implode( ', ', $value );
}
$value = '<img src="distance-logo.svg" alt="distance-logo" class="svg-img"><br/><p>Distance: '.$value.'</p>';
// return
return $value;
}
add_shortcode('acf_if_value_distance', 'acf_shortcode_distance');
What I need is to make value outputs in regards to the given ACF field I am using. Something like:
if( is_array($value) ) {
$value = @implode( ', ', $value );
}
--- IF FIELD = DISTANCE, OUTPUT THIS:
$value = '<img src="distance-logo.svg" alt="distance-logo" class="svg-img"><br/><p>Distance: '.$value.'</p>';
--- IF FIELD = TIME, OUTPUT THIS:
$value = '<img src="time-logo.svg" alt="distance-logo" class="svg-img"><br/><p>Time: '.$value.'</p>';
--- ETC. ETC. FOR EACH NEW FIELD
// return
return $value;
}
Is there any way around doing this? Everything I've tried does not work, and I think re-creating the whole shortcode for the 15+ fields I have is a bit extreme!
I hope someone can guide me on the way, thanks in advance!
I would look at a switch statement for this - https://www.php.net/manual/en/control-structures.switch.php
Avoids a lot of if, else if and makes it easier and cleaner to follow the logic. Which could be nothing if empty or doesn't have a match.