Skip to content Skip to sidebar Skip to footer

Why Does My Foreach Take Forever To Load

This piece of code is run when i hit the submit button on my site to filter out results by address. But for some reason it takes forever for the page to reload, if anyone has any i

Solution 1:

I ended up creating a cron job to fetch the data from the API, store the results in multiple text files and then fetch the data from the text files which is much faster than querying the API multiple times.

query geocode api daily cron job setup

add_action('geocode_daily_event', 'geocode_daily');

function geocode_activation() {
    if ( !wp_next_scheduled( 'geocode_daily_event' ) ) {
        wp_schedule_event( current_time( 'timestamp' ), 'twenty_two_hours', 'geocode_daily_event');
    }
}
add_action('wp', 'geocode_activation');
function geocode_daily(){
    $args = array(
        'meta_query' => array(
            array(
                'key' => 'company_address'
            ),
        ),
    );

    //query execution
    $search_companies = get_users($args);

    foreach ($search_companies as $user){
        $address =  get_user_meta($user->ID, 'company_address', true);
        $address = str_replace(" ", "+", $address);

        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key={YOUR GEOCODE API KEY HERE}";

        $cache_path = get_stylesheet_directory().'/geocode-cache/';
        $filename = $cache_path.md5($url);

        $result  = file_get_contents($url);
        file_put_contents($filename, $result );
    }
}

Function to query the cached files

function prettyAddress($address) {
    $location = array();
    if (empty($address))
        return $location;

    $address = str_replace(" ", "+", $address);
    $url = "https://maps.googleapis.com/maps/api/geocode/json?address=$address&key=AIzaSyCntthdn3101F8RC8RLzv9QxF_tmCvdqNg";

    $cache_path = get_stylesheet_directory().'/geocode-cache/';
    $filename = $cache_path.md5($url);

    // && ( time() - 84600 < filemtime($filename) )
    if( file_exists($filename) ){
        $result = json_decode(file_get_contents($filename), true);

        if (!isset($result['results'][0]['address_components']))
            return $location;
        $components = $result['results'][0]['address_components'];
        foreach ($result['results'][0]['address_components'] as $component) {
            switch ($component['types']) {
                case in_array('street_number', $component['types']):
                    $location['street_number'] = $component['long_name'];
                    break;
                case in_array('route', $component['types']):
                    $location['street'] = $component['long_name'];
                    break;
                case in_array('sublocality', $component['types']):
                    $location['sublocality'] = $component['long_name'];
                    break;
                case in_array('locality', $component['types']):
                    $location['city'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_2', $component['types']):
                    $location['admin_2'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_1', $component['types']):
                    $location['state'] = $component['long_name'];
                    $location['state_code'] = $component['short_name'];
                    break;
                case in_array('postal_code', $component['types']):
                    $location['postal_code'] = $component['long_name'];
                    break;
                case in_array('country', $component['types']):
                    $location['country'] = $component['long_name'];
                    $location['country_code'] = $component['short_name'];
                    break;
            }
        }
    }
    else {
        $result  = file_get_contents($url);
        file_put_contents($filename, $result );
        $result  = json_decode($result , true);

        if (!isset($result['results'][0]['address_components']))
            return $location;
        $components = $result['results'][0]['address_components'];
        foreach ($result['results'][0]['address_components'] as $component) {
            switch ($component['types']) {
                case in_array('street_number', $component['types']):
                    $location['street_number'] = $component['long_name'];
                    break;
                case in_array('route', $component['types']):
                    $location['street'] = $component['long_name'];
                    break;
                case in_array('sublocality', $component['types']):
                    $location['sublocality'] = $component['long_name'];
                    break;
                case in_array('locality', $component['types']):
                    $location['city'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_2', $component['types']):
                    $location['admin_2'] = $component['long_name'];
                    break;
                case in_array('administrative_area_level_1', $component['types']):
                    $location['state'] = $component['long_name'];
                    $location['state_code'] = $component['short_name'];
                    break;
                case in_array('postal_code', $component['types']):
                    $location['postal_code'] = $component['long_name'];
                    break;
                case in_array('country', $component['types']):
                    $location['country'] = $component['long_name'];
                    $location['country_code'] = $component['short_name'];
                    break;
            }
        }
    }
    return $location;
}

Post a Comment for "Why Does My Foreach Take Forever To Load"