-1

I want to make a dynamic select where the user will put state, there will appear the cities of this state, then will put city and will appear the universities of this city for him to choose, how can I do this? I've done this in php, but the code I used in php does not work inside the function to add in the field of woocommerce

  function novo_campo_woocommerce( $checkout ) { 
    echo '<select id="estados" class="form-control" name="estados">
            <option selected disabled>Escolha seu estado</option>';
    $conexao = new PDO('mysql:host=localhost;dbname=teste', 'user', 'password');
    $sql = ('SELECT * FROM tb_estado ORDER BY nome ASC');
    $sql = $conexao->prepare($sql);
    $sql->execute();
    $lista = $sql->fetchAll();
    for ($i=0; $i < count($lista); $i++) { 
        $uf = $lista[$i]['uf'];
        $nome = $lista[$i]['nome'];
        echo "<option value='$uf'>$nome</option>";
    }
    echo '</select>';
    echo '<select class="form-control" name="cidades" id="cidades" required>
              <option value="" selected disabled>Selecione o estado primeiro</option>
          </select>';
    echo '<select class="form-control" name="universidades" id="universidades" required>
              <option value="" selected disabled>Selecione a cidade primeiro</option>
          </select>';
?>
    <script>
           $(function(){
            $("#estados").change(function(){
              var uf = $(this).val();
              $.ajax({
                type: "POST",
                url: "func/exibe_cidade.php?uf="+uf,
                dataType:"text",
                success: function(res){
                  $("#cidades").children(".cidades").remove();
                  $("#universidades").children(".universidades").remove();
                  $("#cidades").append(res);
                  console.log(res);

                }
              });
            });
            $("#cidades").change(function(){
              var id = $(this).val();
              $.ajax({
                type: "POST",
                url: "func/exibe_universidade.php?id="+id,
                dataType:"text",
                success: function(res){
                  $("#universidades").children(".universidades").remove();
                  $("#palestras").children(".palestras").remove();
                }
              });
            });
          });
      </script>
      <?php
}

exibe_cidade.php

<?php

require_once "conn.php";

$uf = $_GET['uf'];
$sql = 'SELECT * FROM tb_cidade WHERE uf = ? ORDER BY nome';
$stm = $conexao->prepare($sql);
$stm->bindValue(1, $uf);
$stm->execute();
$lista = $stm->fetchAll();
for($i=0;$i<count($lista);$i++){ 
    $id = $lista[$i]['id'];
    $nome = $lista[$i]['nome'];

    echo '<option value="'.$id.'" class="cidades">'.$nome.'</option>';
    }
?>
0

Perhaps you could use some jQuery and admin-ajax to do the trick. You would also need to use one of the WooCommerce checkout field filters to add the university select field to the checkout form.

If you're feeling adventurous, you could add a custom end point and use the WP REST API instead of admin-ajax.

I think something along these lines should work. This code is untested, so please modify it to match your needs and setup.

Ajax PHP

function get_select_options() {  
  if ( empty( $_POST['type'] ) || empty( $_POST['selected'] ) ) {
    wp_send_json_error();
  }

  if ( 'state' === $_POST['type'] ) {
    $options_type = 'city';
  } else if ( 'city' === $_POST['type'] ) {
    $options_type = 'university';
  } else {
    $options_type = '';
  }

  if ( ! $options_type ) {
    wp_send_json_error();
  }

  // Do your DB query to get options as an array with value => title pairs
  $options = querySelectOptionsByType( $options_type ); 
  if ( ! $options ) {
    wp_send_json_error();
  }

  wp_send_json_success( array(
    'type' => $options_type,
    'options' => $options
  ) );
}
add_action( 'wp_ajax_get_select_options', 'get_select_options' );
add_action( 'wp_ajax_nopriv_get_select_options', 'get_select_options' );

If you have custom tables in your WP database for the select options, you should be able to access them with $wpdb also.

jQuery,

jQuery(document).ready(function($) {

    $('.conditional-select').on('change',function(event){
        if ( 'state' === this.name ) {
            $('select[name="city"]').empty().hide();
            $('select[name="university"]').empty().hide();
        } else if ( 'city' === this.name ) {
            $('select[name="university"]').empty().hide();
        } else {
            return;
        }
        getSelectOptions( this.name, this.value );
    });

    function getSelectOptions( currentSelect, selectedOption ) {
        var data = {
            'action': 'get_select_options',
            'type': currentSelect,
            'selected': selectedOption
        };
        $.post( ajaxurl, data, function(response) {
            if ( response.success ) {
                var select = $('select[name="' + response.data.type + '"]');
                addOptionsToSelect( response.data.options, select );
                $(select).show();
            }           
        });
    }

    function addOptionsToSelect( options, select ) {
        $(select).empty();
        var optionsHtml = '';
        $.each(options,function(i,option){
            optionsHtml += getOptionString( option.value, option.title );
        });
        $(select).append(optionsHtml);
    }

    function getOptionString( value, title ) {
        return '<option value="' + value + '">' + title + '</option>';
    }

});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.