Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save yuriinalivaiko/7bcfda1feaf971381e465ff39aa67583 to your computer and use it in GitHub Desktop.

Select an option

Save yuriinalivaiko/7bcfda1feaf971381e465ff39aa67583 to your computer and use it in GitHub Desktop.
This code snippet replaces the full address with the city name in the User Location field.
<?php
/**
* Change the user location field value. Save only a city.
*/
add_action( 'wp_footer', function () {
?><script type="text/javascript">
var currentLocationField;
jQuery( '.um_user_location_g_autocomplete' ).on( 'click', function() {
currentLocationField = this;
} );
// on autocomplate.
wp.hooks.addAction( 'um_user_location_after_location_field_set_by_autocomplete', 'um_user_locations', function ( place ) {
for (const component of place.address_components) {
if ( 'locality' === component.types[0] ) {
currentLocationField.value = component.long_name;
break;
}
if ( 'postal_town' === component.types[0] ) {
currentLocationField.value = component.long_name;
break;
}
if ( 'administrative_area_level_3' === component.types[0] ) {
currentLocationField.value = component.long_name;
}
}
} );
// on geocode.
wp.hooks.addFilter( 'um_user_location_formatted_address_set_by_geocode', 'um_user_locations', function( formatted_address, results, position ) {
for (const component of results[0].address_components) {
if ( 'locality' === component.types[0] ) {
return component.long_name;
}
if ( 'postal_town' === component.types[0] ) {
return component.long_name;
}
if ( 'administrative_area_level_3' === component.types[0] ) {
return component.long_name;
}
}
return formatted_address;
} );
</script><?php
}, 20 );
@yuriinalivaiko
Copy link
Author

This gist is a part of the article User Locations - Hooks

You can add this code to the functions.php file in the active theme directory. Skip the opening <?php tag.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment