高级自定义字段/基于另一个acf字段填充选择

时间:2015-05-26 16:27:06

标签: javascript php wordpress drop-down-menu advanced-custom-fields

关于高级自定义字段转发器和选择下拉菜单。我目前有一个围绕汽车的网站。

在wordpress的选项页面中,我有一个转发器块,其中一个文本字段名为“manufacturer”,另一个名为“models”作为文本区域字段。

文本区域在每行上都填充了一个模型,因此在一行中例如:

manufacturer = audi models = A1          A2          A3          A4 等。

在汽车的自定义邮政类型'租赁'上我为制造商和型号做了2个选择下拉菜单。

我可以按照示例#2代码自动填充制造商:

http://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/

工作正常没问题!

然后使用模型下拉选择,仅当制造商选择下拉更改时,然后使用选项页面上的转发器中的模型自动填充它,仅显示基于制造商的模型...

我知道这需要ajax这样做..

我有一个示例代码我正在测试另一周,我可以让它做我想要的但是当你进入单车时它会是空白的,然后当你选择选项然后保存/更新刷新屏幕模型选择下拉列表将再次为空白,虽然通过测试显示它已将数据发送到数据库并已保存。

所以我如何解决这个问题,当我保存汽车贴不会空白的时候?

这是我正在测试的代码

PHP

function acf_admin_enqueue( $hook ) {

$type = get_post_type(); // Check current post type
$types = array( 'lease' ); // 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() .    '/library/dist/js/acf_select.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 models by manufacturer
function model_by_manufacturer( $selected_manufacturer ) {

// Verify nonce
if( !isset( $_POST['pa_nonce'] ) || !wp_verify_nonce( $_POST['pa_nonce'], 'pa_nonce' ) )
die('Permission denied');

// Get manufacturer var
$selected_manufacturer = $_POST['manufacturer'];

// Get field from options page
$manufacturer_and_models = get_field('car_m_and_m', 'options');

// Simplify array to look like: manufacturer => models
  foreach ($manufacturer_and_models as $key => $value) {
    $manufacturer[$value['manufacturer']] = $value['models'];
  }

  // Returns model by manufacturer selected if selected manufacturer exists in array
  if (array_key_exists( $selected_manufacturer, $manufacturer)) {

  // Convert model to array
  $arr_data = explode( ', ', $manufacturer[$selected_manufacturer] );
return wp_send_json($arr_data);

} else {

$arr_data = array();
return wp_send_json($arr_data);
}

die();
}

add_action('wp_ajax_pa_add_areas', 'model_by_manufacturer');
add_action('wp_ajax_nopriv_pa_add_areas', 'model_by_manufacturer');

使用Javascript:

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

/* Add default 'Select one'
$( '#acf-field_5548d019b55cb' ).prepend( $('<option></option>').val('0').html('Select Manufacturer').attr({ selected: 'selected', disabled: 'disabled'}) );
*/
/**
 * Get manufacturer option on select menu change
 *
 */
$( '#acf-field_5548d019b55cb' ).change(function () {

    var selected_manufacturer = ''; // Selected value

    // Get selected value
    $( '#acf-field_5548d019b55cb option:selected' ).each(function() {
        selected_manufacturer += $( this ).text();
    });

    $( '#acf-field_5548da7058203' ).attr( 'disabled', 'disabled' );

    // If default is not selected get models for selected manufacturer
    if( selected_manufacturer !== 'Select Manufacturer' ) {
        // Send AJAX request
        data = {
            action: 'pa_add_areas',
            pa_nonce: pa_vars.pa_nonce,
            manufacturer: selected_manufacturer,
        };

        // Get response and populate models select field
        $.post( ajaxurl, data, function(response) {

            if( response ){
                /* Disable 'Select model' field until country is selected
                $( '#acf-field_5548da7058203' ).html( $('<option></option>').val('0').html('Select Model').attr({ selected: 'selected', disabled: 'disabled'}) );
                */
                // Add models to select field options
                $.each(response, function(val, text) {
                    $( '#acf-field_5548da7058203' ).append( $('<option></option>').val(text).html(text) );
                });

                // Enable 'Select Model' field
                $( '#acf-field_5548da7058203' ).removeAttr( 'disabled' );
            }
        });
    }

}).change();
});

我认为它与Javascript有关?

任何建议或帮助将不胜感激,

提前谢谢。

[R

1 个答案:

答案 0 :(得分:1)

我知道这个问题有点陈旧但它有一些赞成,所以我认为值得为这个问题找到答案。

当您编辑“租约”时post,设置制造商然后使用AJAX从其值填充模型字段,模型选择框将填充所选制造商的值。此值未在服务器端验证为有效&#39;选择,因此它正确地保存在数据库中作为post meta。

再次加载编辑屏幕时,未选择模型的当前值,因为当高级自定义字段为选择字段服务器端生成HTML时,没有预先选择的选项。来自fields / select.php的以下PHP walker通过字段$choices$values传递给正在编辑的字段/帖子:

function walk( $choices, $values ) {

    // bail ealry if no choices
    if( empty($choices) ) return;


    // loop
    foreach( $choices as $k => $v ) {

        // optgroup
        if( is_array($v) ){

            // optgroup
            echo '<optgroup label="' . esc_attr($k) . '">';


            // walk
            $this->walk( $v, $values );


            // close optgroup
            echo '</optgroup>';


            // break
            continue;

        }


        // vars
        $search = html_entity_decode($k);
        $pos = array_search($search, $values);
        $atts = array( 'value' => $k );


        // validate selected
        if( $pos !== false ) {

            $atts['selected'] = 'selected';
            $atts['data-i'] = $pos;

        }


        // option
        echo '<option ' . acf_esc_attr($atts) . '>' . $v . '</option>';

    }

}

由于您的字段在AJAX使用制造商字段填充之前没有选择,因此不会设置所选属性。您应该为模型字段服务器端填充选项,以便在保存后保留后编辑屏幕上的值。例如:

function load_current_models($field){

  /** Get posts current manufacturer */
  $current_manufact = get_field('manufacturer');

  /** Manufacturer must be set */
  if($current_manufact) {

    /** Get manufacturers and models from options page */
    $all_models = get_field('car_m_and_m', 'options');

    /** Look for manufacturers models **/
    foreach($all_models as $manufacturer){
      if($manufacturer['manufacturer'] == $current_manufact){
        $field['choices'] = explode(', ', $model['models']);
        return $field;
      } 
    }
  }

  /** Disable models by default */
  $field['disabled'] = true;
  return $field;
}

add_filter('acf/load_field/key=field_5548da7058203', 'load_current_models');

如果没有设置制造商,这也会在加载时禁用模型字段,我假设有一个新帖子,允许您从JS中删除.change()调用,导致制造商选择更改也会在加载时触发事件。这将在传递服务器端之后附加重复的模型选项。

你应该更新JS以删除旧的&#39;制造商更改的选项如果您选择了制造商然后将其更改为另一个,则两个制造商模型都将包含在选项中。例如:

// Get models field jQuery object
var models = $('#acf-field_5548da7058203');

// Disable while waiting for server
models.prop('disabled', true);

// Remove old model field options
models.find('option').each(function(){
  if($(this).val() != 0) $(this).remove();
});

// Get response and populate models select field
$.post( ajaxurl, data, function(response) {
  if( response ){

    // Add models to select field options
    $.each(response, function(val, text) {
      models.append( $('<option></option>').val(text).html(text) );
    });

    // Enable 'Select Model' field
    models.removeAttr( 'disabled' );
  }
});
相关问题