Categories : General

Hi, If you have product variation data and want to match this data to existing product variations without stock code this code is very useful for you.

<?php
# initialize wordpress if you are working out of wordpress context
require_once __DIR__ . '/wp-load.php';

# get products

$products = wc_get_products( array(
    'limit' => -1,
    'status' => 'publish',
    'return' => 'ids',
    'orderby' => 'date',
    'order' => 'DESC',
    'type' => 'variable',
) );


# get product variations
foreach ($products as $product) {


    $product_variation_data = [
        ["Sıcaklık" => "1200 °C","Colore" => "Arancio Fluorescente"],
        ["Sıcaklık" => "1000 °C","Colore" => "Arancio"],
    ];


    foreach ($product_variation_data as $product_variation) {

        $query_metas = ['relation' => 'AND'];


        foreach ($product_variation as $key => $datum) {

            $taxonomy = 'attribute_' . wc_attribute_taxonomy_name($key); // The taxonomy slug
            $attr_label = ucfirst($key); // attribute label name
            $attr_name = (wc_sanitize_taxonomy_name($key)); // attribute slug

            $attribute_value_name = ucfirst($datum);
            $attribute_value_slug = sanitize_title($datum);

            $query_metas[] = array(
                'key' => $taxonomy,
                'value' => $attribute_value_slug,
                'compare' => '=',
            );

        }

        $variations = new WP_Query( array(
            'post_status' => 'publish',
            'return' => 'ids',
            'post_type' => 'product_variation',
            'post_parent' => $product,
            'meta_query' => $query_metas
        ));

        if ($variations->have_posts()) {
            print_r($variations->posts);
        }

    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *