php - 基于 WooCommerce 中所选品牌的动态选择字段选项

标签 php jquery ajax wordpress woocommerce

在 woocommerce 中,我有 2 个选择字段:

  • 第一个是“汽车品牌”,
  • 第二个是这些汽车品牌的“车型”。

我想做的是动态获取所选“汽车品牌”的“汽车型号”

“汽车品牌”来自 WooCommerce 产品属性分类法。对于每个“汽车品牌”,相关的“汽车型号”是该产品属性分类的术语。

以下是“汽车品牌”的代码(第一个选择字段):

$attributes =  wc_get_attribute_taxonomies();

if($attributes) {
    echo '<select id="car-brands"><option value="noselection">Car Brand</option>';
    foreach ( $attributes as $attribute ) {
        echo '<option value="' . $attribute->attribute_name . '">' . $attribute->attribute_label . '</option>';
    }
    echo '</select>';
}

以及生成的 html 示例代码:

<select id="car-brands">
    <option value="noselection">Car Brand</option>
    <option value="toyota">TOYOTA</option>
    <option value="lexus">LEXUS</option>
</select>

然后是“汽车型号”的代码(第二个选择字段):

$selected_attribute_name = 'toyota';
$taxonomy = 'pa_' . $selected_attribute_name;
$term_names = get_terms( array( 'taxonomy' => $taxonomy, 'fields' => 'names' ) );

echo '<select id="car-models"><option value="noselection">Car Model</option>';
echo '<option>' . implode( '</option><option>', $term_names ) . '</option>';
echo '</select>';

以及生成的 html 示例代码:

<select id="car-models">
    <option value="noselection">Car Model</option>
    <option value="toyota">AVENSIS</option>
    <option value="lexus">CAMRY</option>
</select>

如您所见,我正在获取“丰田”品牌的特定车型,因为我已将“丰田”硬编码为“汽车品牌”:

$selected_attribute_name = 'toyota';

所以我想要的是将 $selected_attribute_name 作为动态变量,因此当用户选择汽车品牌“LEXUS”或“TOYOTA”时,第二个选择字段会动态加载相关术语(选项)

我发现了很多相关的线程,但我无法理解如何让它在我的案例中发挥作用。

如何让动态“汽车型号”根据所选汽车品牌选择字段选项?

<小时/>

编辑

我的所有 php 都在一个 Action 钩子(Hook)函数中,如下所示:

function _themename_woocommerce_custom_filter() {
    $attributes =  wc_get_attribute_taxonomies();

    if($attributes) {
        echo '<select id="car-brands"><option value="noselection">Car Brand</option>';
        foreach ( $attributes as $attribute ) {
            echo '<option value="' . $attribute->attribute_name . '">' . $attribute->attribute_label . '</option>';
        }
        echo '</select>';
    }

    $selected_attribute_name = '';
    $taxonomy = 'pa_' . $selected_attribute_name;
    $term_names = get_terms( array( 'taxonomy' => $taxonomy, 'fields' => 'names' ) );

    echo '<select id="car-models"><option value="noselection">Car Model</option>';
    echo '<option>' . implode( '</option><option>', $term_names ) . '</option>';
    echo '</select>';
}
add_action( 'woocommerce_before_shop_loop', '_themename_woocommerce_custom_filter', 3 );

最佳答案

下面使用Ajax从选定的“汽车品牌”中获取对应的术语(产品属性分类),动态生成“汽车型号”选择字段选项(所选术语产品属性分类):

// Display 2 select fields (car brands and car models)
add_action( 'woocommerce_before_shop_loop', 'before_shop_loop_action_callback', 3 );
function before_shop_loop_action_callback() {
    if( $attributes =  wc_get_attribute_taxonomies() ) {

        ## 1st dropdown

        echo '<select id="car-brands" style="min-width:100px;"><option value="">' . __("Car Brand"). '</option>';

        // Loop through attribute taxonomies
        foreach ( $attributes as $attribute ) {
            echo '<option value="' . $attribute->attribute_name . '">' . $attribute->attribute_label . '</option>';
        }
        echo '</select>';

        ## 2nd dropdown

        echo '<select id="car-models" style="min-width:100px;"><option value=""> … </option></select>';
    }
}

// jQuery / Ajax (client side)
add_action( 'wp_footer', 'car_brand_selectors_script' );
function car_brand_selectors_script() {
    ?>
    <script type="text/javascript">
    jQuery(function( $ ) {
        if (typeof woocommerce_params === 'undefined')
            return false;

        var b = 'select#car-brands', // 1st field
            m = 'select#car-models', // 2nd field
            r = $(m).html(); // Original 2nd field select options

        function ajaxSendCarBrand( carBrand ) {
            $.ajax({
                url: woocommerce_params.ajax_url,
                type : 'POST',
                data : {
                    'action' : 'get_brand_terms',
                    'car_brand' : carBrand
                },
                success: function( response ) {
                    var options = $.parseJSON(response),
                        opt     = '';

                    if ( $.isEmptyObject(options) ) {
                        $(m).html(r);
                    } else {
                        $.each( options, function( key, value ){
                            opt += '<option value="'+key+'">'+value+'</option>';
                        });
                        $(m).html(opt);
                    }
                }
            });
        }

        // On change live event
        $( document.body ).on( 'change', b, function() {
            ajaxSendCarBrand($(this).val());
        });
    });
    </script>
    <?php
}

// WP AJAX HANDLER (Server side)
add_action('wp_ajax_get_brand_terms', 'get_car_brand_models');
add_action('wp_ajax_nopriv_get_brand_terms','get_car_brand_models');
function get_car_brand_models() {
    if( isset($_POST['car_brand']) ) {
        $brand    = wc_clean( $_POST['car_brand'] );
        $taxonomy = wc_attribute_taxonomy_name($brand);
        $options  = [];

        if( taxonomy_exists( $taxonomy ) ) {
            $terms   = get_terms( array( 'taxonomy' => $taxonomy ) );

            foreach( $terms as $term ){
                $options[$term->slug] = $term->name;
            }
        }
        echo json_encode( $options );
    }
    wp_die();
}

代码位于事件子主题(或事件主题)的functions.php 文件中。经过测试并有效。

关于php - 基于 WooCommerce 中所选品牌的动态选择字段选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61939246/

相关文章:

jquery - 随机背景图片 CSS3

javascript - 为什么一个按钮会导致我的整个网页重新加载?

ruby-on-rails - 如何使用 rails 远程 : true parameter with JSON?

php - 我已经搜索了 FOSUserBundle 私有(private)资料,但无济于事

php - mysqli_real_escape_string 安全吗?

JavaScript foreach 键值数组

javascript - 使用 ZombieJS 从异步点击事件触发的 Ajax 获取 Http 错误

javascript - AJAX 后 - Codeigniter

php - CakePHP 模型加载需要一段时间

php - 用 PHP 显示多张图片