Guest User

Untitled

a guest
Mar 7th, 2019
85
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function acf_load_select_country( $field ) {
  2.   // Reset choices
  3.   $field['choices'] = array();
  4.  
  5.   // Get field from options page
  6.   $countries_and_areas = get_field('countries_and_areas', 'options');
  7.  
  8.   // Get only countries in array
  9.   foreach ($countries_and_areas as $key => $value) {
  10.     $countries[] = $value['country'];
  11.   }
  12.  
  13.   // Sort countries alphabetically
  14.   natsort( $countries );
  15.  
  16.   // Populate choices
  17.   foreach( $countries as $choice ) {
  18.     $field['choices'][ $choice ] = $choice;
  19.   }
  20.  
  21.   // Return choices
  22.   return $field;
  23.  
  24. }
  25.  
  26.  
  27. // Populate select field using filter
  28. add_filter('acf/load_field/name=field_5c7f1915175b2', 'acf_load_select_country');
  29.  
  30.  
  31.  
  32.  
  33. function acf_admin_enqueue( $hook ) {
  34.  
  35.   $type = get_post_type(); // Check current post type
  36.   $types = array( 'post' ); // Allowed post types
  37.  
  38.   if( !in_array( $type, $types ) )
  39.       return; // Only applies to post types in array
  40.  
  41.   wp_enqueue_script( 'populate-area', get_stylesheet_directory_uri() . '/assets/js/autopopulate.js' );
  42.  
  43.   wp_localize_script( 'populate-area', 'pa_vars', array(
  44.         'pa_nonce' => wp_create_nonce( 'pa_nonce' ), // Create nonce which we later will use to verify AJAX request
  45.       )
  46.   );
  47. }
  48.  
  49. add_action( 'admin_enqueue_scripts', 'acf_admin_enqueue' );
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56. // Return areas by country
  57. function area_by_country( $selected_country ) {
  58.  
  59.   // Verify nonce
  60.   if( !isset( $_POST['pa_nonce'] ) || !wp_verify_nonce( $_POST['pa_nonce'], 'pa_nonce' ) )
  61.     die('Permission denied');
  62.  
  63.   // Get country var
  64.   $selected_country = $_POST['country'];
  65.  
  66.   // Get field from options page
  67.   $countries_and_areas = get_field('countries_and_areas', 'options');
  68.  
  69.   // Simplify array to look like: country => areas
  70.   foreach ($countries_and_areas as $key => $value) {
  71.     $countries[$value['country']] = $value['area'];
  72.   }
  73.  
  74.   // Returns Area by Country selected if selected country exists in array
  75.   if (array_key_exists( $selected_country, $countries)) {
  76.  
  77.     // Convert areas to array
  78.     $arr_data = explode( ', ', $countries[$selected_country] );
  79.     return wp_send_json($arr_data);
  80.  
  81.   } else {
  82.  
  83.     $arr_data = array();
  84.     return wp_send_json($arr_data);
  85.   }
  86.  
  87.   die();
  88. }
  89.  
  90. add_action('wp_ajax_pa_add_areas', 'area_by_country');
  91. add_action('wp_ajax_nopriv_pa_add_areas', 'area_by_country');
RAW Paste Data