How to get the state from the input field

Location:

I was assigned a task to retrieve only the state from a input field that is auto populated by the google maps API. So what am I talking about, eg. a user would fill in the form’s input (for location) and google would automatically fill in the city, state and country. That’s great and works a treat, it’s saved in the database post_meta eg. Melbourne VIC, Australia and in the field name of ‘user_city’.

*Note* This is all done within WordPress functions.php file.

How to tackle the task

The task should you choose/decide to accept it, “get the state only and set it to a new field and save it to the database”

1. first I set a variable $char to the ACF’s get_field(‘user_city’) from the database.

2. next, using a regex function I only target the capital letters from the variable $char eg. ‘user_city’= Melbourne VIC , Australia and add the variable named $matches which matches my regex function

output eg. VIC

3. now that I have the capital letters from the preg_match() eg. VIC (the state), I use a WordPress
function update_post_meta() which updates the post meta field based on the given post ID and saves it to the database. For the post_id I use get_the_ID() which will retrieve the ID of the current item in the WordPress Loop, next I name the post meta “seller_state” and last the array that comes back from the preg_match function.
You can try regular expression here

4. Last I warp it in a get_state function and turn it in a shortcode so I can add it anywhere I need throughout the site.
echo do_shortcode(‘[get_state]’);

function get_state() {

    // get from database - set to variable
    $char = get_field('user_city');

    // get only 3 capital letters or 2
    preg_match('/(([A-Z]{3})|([A-Z]{2})|[0-9]{5})+/', $char, $matches);

    update_post_meta ( $post_id = get_the_ID(), 'seller_state', $matches[1] );
    
    //  print_r($matches);
   
     echo($matches[1]);
    }
  add_shortcode( 'get_state', 'get_state' );

Now that the state is saved within the database in a new field called ‘seller_sate’, if you were using facetwp or any other filtering search plugin you could now get that data add the new facet and filter by state. Hope this helps someone and thanks for visiting!

Leave a Reply

Your email address will not be published. Required fields are marked *

Get a free proposal for your business