如何编辑WooCommerce结账字段

时间:2019-05-21 作者:Faillen

我想做一个动态选择,用户将把状态放在哪里,会出现这个状态的城市,然后会把城市,会出现这个城市的大学供他选择,我怎么做?我已经在php中完成了这项工作,但我在php中使用的代码在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\\u 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>\';
    }
?>

1 个回复
最合适的回答,由SO网友:Antti Koskinen 整理而成

也许您可以使用一些jQuery和admin-ajax 做这个把戏。您还需要使用WooCommerce checkout field filters 要将“大学选择”字段添加到签出表单中。

如果您有冒险精神,可以添加一个自定义终点并使用WP REST API 而不是admin-ajax.

我认为这样的做法应该奏效。此代码未经测试,请修改它以符合您的需要和设置。

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\' );
如果WP数据库中有用于选择选项的自定义表,则应该能够access them 具有$wpdb 而且

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>\';
    }

});

相关推荐