Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function acf_load_select_country( $field ) {
- // Reset choices
- $field['choices'] = array();
- // Get field from options page
- $countries_and_areas = get_field('countries_and_areas', 'options');
- // Get only countries in array
- foreach ($countries_and_areas as $key => $value) {
- $countries[] = $value['country'];
- }
- // Sort countries alphabetically
- natsort( $countries );
- // Populate choices
- foreach( $countries as $choice ) {
- $field['choices'][ $choice ] = $choice;
- }
- // Return choices
- return $field;
- }
- // Populate select field using filter
- add_filter('acf/load_field/name=field_5c7f1915175b2', 'acf_load_select_country');
- function acf_admin_enqueue( $hook ) {
- $type = get_post_type(); // Check current post type
- $types = array( 'post' ); // Allowed post types
- if( !in_array( $type, $types ) )
- return; // Only applies to post types in array
- wp_enqueue_script( 'populate-area', get_stylesheet_directory_uri() . '/assets/js/autopopulate.js' );
- wp_localize_script( 'populate-area', 'pa_vars', array(
- 'pa_nonce' => wp_create_nonce( 'pa_nonce' ), // Create nonce which we later will use to verify AJAX request
- )
- );
- }
- add_action( 'admin_enqueue_scripts', 'acf_admin_enqueue' );
- // Return areas by country
- function area_by_country( $selected_country ) {
- // Verify nonce
- if( !isset( $_POST['pa_nonce'] ) || !wp_verify_nonce( $_POST['pa_nonce'], 'pa_nonce' ) )
- die('Permission denied');
- // Get country var
- $selected_country = $_POST['country'];
- // Get field from options page
- $countries_and_areas = get_field('countries_and_areas', 'options');
- // Simplify array to look like: country => areas
- foreach ($countries_and_areas as $key => $value) {
- $countries[$value['country']] = $value['area'];
- }
- // Returns Area by Country selected if selected country exists in array
- if (array_key_exists( $selected_country, $countries)) {
- // Convert areas to array
- $arr_data = explode( ', ', $countries[$selected_country] );
- return wp_send_json($arr_data);
- } else {
- $arr_data = array();
- return wp_send_json($arr_data);
- }
- die();
- }
- add_action('wp_ajax_pa_add_areas', 'area_by_country');
- add_action('wp_ajax_nopriv_pa_add_areas', 'area_by_country');
Add Comment
Please, Sign In to add comment