亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

基于 WooCommerce 中所選品牌的動態選擇字段選項

基于 WooCommerce 中所選品牌的動態選擇字段選項

PHP
心有法竹 2023-04-15 11:06:45
在 woocommerce 中,我有 2 個選擇字段:第一個是“汽車品牌”,第二個是這些的“汽車模型” Car Brands。我想做的是為所選的“汽車品牌”動態獲取“汽車型號”“汽車品牌”來自 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>如您所見,我正在獲取“toyota”品牌的特定車型,因為我已將“toyota”硬編碼為“Car brand”:$selected_attribute_name = 'toyota';所以我想要的是作為$selected_attribute_name一個動態變量,所以當用戶選擇汽車品牌“LEXUS”或“TOYOTA”時,第二個選擇字段會動態加載相關術語(選項)。我發現了很多相關的線程,但我無法理解如何讓它適用于我的案例。如何讓動態“汽車模型”根據所選汽車品牌選擇字段選項?
查看完整描述

2 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

下面使用Ajax從選中的“汽車品牌” (產品屬性分類法)中獲取對應的terms ,動態生成“car model”選擇字段選項(選中的產品屬性分類法的terms):


// 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 文件。測試和工作。


查看完整回答
反對 回復 2023-04-15
?
瀟瀟雨雨

TA貢獻1833條經驗 獲得超4個贊

在這里看一個有效的 ajax 示例。


Javascript 部分:


jQuery('#car-brands').change(function() {

    let carBrandName = jQuery(this).val();

    YourFunctionNameHere(carBrandName);

});


//function to execute

function YourFunctionNameHere(carBrandName) {

    //formdata variable consists of

    //action: this is ajax action name for WordPress which we define in PHP with a callback function with same name. See in PHP code part.

    //brandName: this is your custom post attributes name

    let formdata = "action=get_car_models&brandName="+carBrandName;

    jQuery.ajax({

        type: "POST",

        url: ajaxurl, // since WordPress version 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php

        data: formdata,

        cache: false,

        success: function(response, textStatus, jqXHR) {

            jQuery("#car-models").html(response);

        },

        error: function(jqXHR, textStatus, errorThrown) {

            //do stuff here in case of error

        }

    });

}

PHP部分:


 //here wp_ajax is the required prefix for your custom actions

 //first parameter is action name with wp_ajax prefix

 //second parameter is callback function to execute with same name as your action

 //for example if your action name is wp_ajax_get_car_models then your callback will be get_car_models

add_action( 'wp_ajax_get_car_models', 'get_car_models' );


function get_car_models() {

    global $wpdb; // this is how you get access to the database

//require_once any files here in which the below code is available or just write your code here.

    $selected_attribute_name = $_POST['brandName'];

    $taxonomy = 'pa_' . $selected_attribute_name;

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

    $html = '';

    $html .= '<select id="car-models"><option value="noselection">Car Model</option>';

    $html .= '<option>' . implode( '</option><option>', $term_names ) . '</option>';

    $html .= '</select>';

    echo $html;

    wp_die(); // this is required to terminate immediately and return a proper response


}


查看完整回答
反對 回復 2023-04-15
  • 2 回答
  • 0 關注
  • 163 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號