Control which parts of a location string is shown.

Description/Instructions

Add this php script into your functions.php to be able to control which parts of a location is shown.

 

Instructions

This script will add a mod called “get address parts”.

Depending on the values you enter in the mod it will only show that part of the location string.

For example I use the “full address” location, and set the “get address parts” to the value: 1, -1

This gives me the first and last parts of the location string, which is: city, country

Entering different values into the mod will give you different parts of the location string.

Only thing you have to be cautious about is the all users enter the same type of location value. If some enter a shorter or longer value the mod could remove unwanted parts. Hence why I just use it for the first and last part, since they are always the same.
 
NOTE: I'm using mapbox. Not sure how Google maps output the strings - but I'm thinking it's the same.

add_filter( 'voxel/dynamic-tags/modifiers', function( $modifiers ) {
class Get_Address_Parts extends \Voxel\Dynamic_Tags\Base_Modifier {
public function get_label(): string {
return 'Get address parts';
}
public function get_key(): string {
return 'get_address_parts';
}
public function get_arguments(): array {
return [
'parts' => [
'type' => \Voxel\Form_Models\Text_Model::class,
'label' => _x( 'Enter parts, e.g. 1,3', 'modifiers', 'voxel-backend' ),
'classes' => 'x-col-12',
],
];
}
public function apply( $value, $args, $group ) {
$parts = explode( ', ', $value );
$requested = array_filter( array_map( 'intval', explode( ',', $args[0] ?? '' ) ) );
return join( ', ', array_filter( array_map( function( $i ) use ( $parts ) {
return $i < 0 ? ( $parts[ count( $parts ) + $i ] ?? null ) : ( $parts[ $i - 1 ] ?? null );
}, $requested ) ) );
}
}
$modifiers['get_address_parts'] = \Get_Address_Parts::class;
return $modifiers;
} );

  • PHP
Copy Code

Let's Chat About this Snippet