0

So I have the following snippet which I'm using to build a URL structure:

$map_url = 'https://google.com/maps/search/'.get_field('brand', $office).
' '.get_field('location', $office).
' '.get_field('address_line_1', $office).
', '.get_field('address_line_2', $office).
', '.get_field('city', $office).
', '.get_field('state', $office).
', '.get_field('zip_code', $office).
', '.get_field('country', $office);

When there are fields missing, I get the following outputs:

Edificio World Trade Center, Torre B, Avenida Francisco de Orellana, Guayaquil, , , Ecuador

Is there anyway to avoid appending the commas if a field is empty? Or is there a better way to structure my URL using all the ACF fields?

ikiK
  • 6,328
  • 4
  • 20
  • 40
Tripp
  • 67
  • 6

1 Answers1

1

I would use an array with implode() so we don't need to check each value manually.

We can use array_filter() to remove any 'invalid' (empty) values.

Take a look at this example

<?php

// Empty array
$res = [];

// Push some values
$res[] = 'location';
$res[] = 'Guayaquil';
$res[] = '';            // Empty string to 'fake' invalid get_field result

// Remove any empty values
$res = array_filter($res);

// Implode the array with ', '
$res = implode(', ', $res);

// Show result
echo $res; 

// location, Guayaquil

Try it online!

0stone0
  • 34,288
  • 4
  • 39
  • 64