如何通过 woocommerce 中的属性获取变体 ID

how to get variation id by attributes in woocommerce

我想在用户点击我的属性时找到ID并可验证,请帮助。 例如,我们有两个属性: 区域 = ars 充值金额=100ars

当两者都选择时,必须返回一个有效的ID

我的代码:

<?php $attributes = $product->get_attributes() // GET ALL ATRIBUTES ?>
                        <?php foreach ($attributes as $key => $value): ?>
                            <?php $attribute_name_ = preg_replace('/pa_/', '', $key); // GET ATTRIBUTE NAME


                            ?>

                            <div class="<?= ($attribute_name_ == 'regions') ? 'region' : 'charge'; ?>">


                                <?php $attribute_name = wc_get_product_terms(get_the_ID(), $key);

                                $attribute_slug = wc_get_product_terms(get_the_ID(), $key, array('fields' => 'slugs')); // GET ATTRIBUTE SLUG


                                ?>
                                <?php for ($i = 0; $i < count($attribute_name); $i++): // array_slice BECAUSE ARRAY INDEX IS NOT SEQUENCIAL

                                    $slug = array_slice($attribute_slug, $i, 1);


                                    $atribute_list = [];
                                    if ($attribute_name_ == 'regions') {

                                        $atribute_list['attribute_pa_regions'] = $slug['0'];
                                    }
                                    if ($attribute_name_ == 'charge-amount') {
                                        $atribute_list['attribute_pa_charge-amount'] = $slug['0'];
                                    }

//                                    echo find_matching_product_variation_id($product, $atribute_list);


                                    ?>


                                    <?php
                                    if ($attribute_name_ == 'regions') {


                                        ?>
                                        <div id="<?= $slug['0'] ?>"
                                             class="region-item">

                                            <img src="https://upload.wikimedia.org/wikipedia/en/a/a4/Flag_of_the_United_States.svg"
                                                 alt="">
                                            <span>
                        <?php

                        $name = array_slice($attribute_name, $i, 1);
                        echo $name[0]->name;

                        ?>
                    </span>
                                        </div>
                                        <?php

                                    }


                                    if ($attribute_name_ == 'charge-amount') {

                                        $atribute_list['attribute_pa_charge-amount'] = $slug['0'];
                                        ?>

                                        <div id="<?= $slug['0'] ?>"
                                             class="charge-item">

                                            <?php

                                            $name = array_slice($attribute_name, $i, 1);
                                            echo $name[0]->name;

                                            ?>

                                        </div>
                                        <?php
                                    }


                                    ?>


                                <?php endfor ?>
                            </div>
                        <?php endforeach ?>

我这里只单独显示属性,现在我想在点击相关属性时显示ID和可验证信息或包含在一个变量中。

我的代码输出是这样的:

我是这样解决问题的 我创建了一个函数,它使用产品 ID 和国家/地区属性 ID 提取其收费金额的属性,并使用 Ajax 调用。 然后通过另一个功能发送价格和有关收费金额的信息,最后就可以了

我的鳕鱼:

<?php


                    foreach ($attributes as $key => $value):
                        $attribute_name_ = preg_replace('/pa_/', '', $key); // GET ATTRIBUTE NAME


                        ?>

                        <div class="<?= ($attribute_name_ == 'regions') ? 'region' : 'charge'; ?>">


                            <?php $attribute_name = wc_get_product_terms(get_the_ID(), $key);

                            $attribute_slug = wc_get_product_terms(get_the_ID(), $key, array('fields' => 'slugs')); // GET ATTRIBUTE SLUG
                            $attribute_name = wc_get_product_terms(get_the_ID(), $key); // GET ATTRIBUTE SLUG
                            $attribute_thumbnail_id = wc_get_product_terms(get_the_ID(), $key, array('fields' => 'term_id')); // GET ATTRIBUTE SLUG


                            for ($i = 0; $i < count($attribute_name); $i++): // array_slice BECAUSE ARRAY INDEX IS NOT SEQUENCIAL

                                $slug = array_slice($attribute_slug, $i, 1);


                                if ($attribute_name_ == 'regions') {

                                    $thumb_id = get_term_meta($attribute_name[$i]->term_id);

                                    $thumb_id_ = get_term_meta($attribute_name[$i]->term_id, 'product_attribute_image', true);

                                    $img_src = wp_get_attachment_thumb_url($thumb_id_);

                                    ?>
                                    <div id="<?= $slug['0'] ?>"
                                         class="region-item">

                                        <img src="<?= $img_src ?>"
                                             alt="">
                                        <span>
                    <?php

                    $name = array_slice($attribute_name, $i, 1);
                    echo $name[0]->name;

                    ?>
                </span>
                                    </div>
                                    <?php

                                }
                                ?>


                            <?php endfor ?>
                        </div>
                    <?php endforeach ?>


                    <div class="buy-btn">
                        <div class="price-section">
                            <div class="price-lable">
                                price : 
                            </div>
                            <div class="price">

                            </div>
                        </div>


                        <a class="add-to-cart" value="">add to cart</a>
                    </div>

我的功能:

function get_varible_data()
{

    $producit_id = $_POST['p_id'];
    $region_id = $_POST['region_id'];

    $product = wc_get_product($producit_id);

    $attributes = $product->get_attributes();
    $get_variation_attributes = $product->get_variation_attributes();
    $available_variations = $product->get_available_variations();

    foreach ($available_variations as $available_variation) {
        $regions = $available_variation['attributes']['attribute_pa_regions'];
        $varible_id = $available_variation['variation_id'];
        $charge = $available_variation['attributes']['attribute_pa_charge-amount'];
        $display_price = $available_variation['display_price'];


        $pa_charge_amount_ = 'pa_charge-amount';
        $pa_charge_amount_meta = get_post_meta($available_variation['variation_id'], 'attribute_' . $pa_charge_amount_, true);
        $pa_charge_amount_term = get_term_by('slug', $pa_charge_amount_meta, $pa_charge_amount_);


        if ($region_id === $regions) {

            $vari_g[] = array(
                'group' => $region_id,
                'price' => $display_price,
                'slug' => $charge,
                'id' => $varible_id,
                'name' => $pa_charge_amount_term->name,
            );

            $html = '<div id="' . $varible_id . '" class="charge-item">' . $pa_charge_amount_term->name . '</div>';

            echo $html;
        }
    }

    wp_die();

}

add_action("wp_ajax_get_varible_data", "get_varible_data");
add_action("wp_ajax_nopriv_get_varible_data", "get_varible_data");

function get_varible_ch_data()
{


    $variation_id = $_POST['charge_id'];
    $price = get_post_meta($variation_id, '_price', true);

    echo $price;

    wp_die();

}

add_action("wp_ajax_get_varible_ch_data", "get_varible_ch_data");
add_action("wp_ajax_nopriv_get_varible_ch_data", "get_varible_ch_data");

和我的 ajax :

<script>

            function request_ajax_call_varible(metodth, id) {

                $('.card-buy').css('cursor', 'wait');
                var hastag = '#';
                var ajaxurl = "<?php bloginfo('url'); ?>/wp-admin/admin-ajax.php";

                if (metodth === 'get_var_id') {

                    jQuery.ajax({

                        type: "POST",
                        url: ajaxurl,
                        dataType: 'html',
                        data: {
                            action: "get_varible_data",
                            p_id: <?= get_the_id() ?>,
                            region_id: id,

                        },


                        success: function (response) {

                            jQuery(hastag + id).addClass('active');
                            jQuery('.charge').html(response);

                            $('.card-buy').css('cursor', 'default');

                        }
                    })
                }

                if (metodth === 'get_price') {

                    var before_link = '<?php bloginfo('url'); ?>/cart/?add-to-cart=';
                    var link = before_link + id;
                    jQuery.ajax({

                        type: "POST",
                        url: ajaxurl,
                        dataType: 'html',
                        data: {
                            action: "get_varible_ch_data",
                            charge_id: id,
                        },


                        success: function (response) {

                            jQuery('.price').html(toFarsiNumber(numberWithCommas(response)) + '<span class="price-symbole">تومان </span>');


                            jQuery(hastag + id).addClass('active');
                            jQuery("a.add-to-cart").attr("href", link)
                            $('.card-buy').css('cursor', 'default');

                        }
                    })
                }
            }

            jQuery('.region-item').click(function (e) {

                $('div.region-item').removeClass('active');
                request_ajax_call_varible('get_var_id', jQuery(this).attr('id'))

            });


            $('div.charge').on('click', 'div.charge-item', function () {

                $('div.charge-item').removeClass('active');
                request_ajax_call_varible('get_price', jQuery(this).attr('id'))

            })


            function numberWithCommas(x) {
                return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            }


            function toFarsiNumber(n) {
                const farsiDigits = ['۰', '۱', '۲', '۳', '۴', '۵', '۶', '۷', '۸', '۹'];

                return n
                    .toString()
                    .replace(/\d/g, x => farsiDigits[x]);
            }

            var first_item = $($('.region-item')[0]);
            first_item.ready(function () {

                first_item.addClass('active');
                request_ajax_call_varible('get_var_id', first_item.attr('id'))
            });


            $(document).ready(function () {
                setTimeout(function () {
                    var first_cha = $($('.charge-item')[0]);
                    first_cha.ready(function () {

                        first_cha.addClass('active');

                        request_ajax_call_varible('get_price', first_cha.attr('id'))
                    });
                }, 1000);
            })


        </script>

希望这个方法对你有用。 如果你有其他方法,请告诉我 谢谢