Вот что я сделал на данный момент:
Я настроил поля повторителя ACF на странице редактирования продукта.
Я написал функцию для создания вариантов продукта при сохранении, используя данные из полей повторителя ACF.
как это выглядит: Экран
Варианты создаются, но заголовки вариантов заданы неправильно. Каждый вариант должен иметь заголовок, включающий значение расстояния, и должен быть установлен соответствующий атрибут. Это делает варианты недействительными, поэтому они не отображаются во внешнем интерфейсе. Название варианта
Вот код, который я сейчас использую:
Код: Выделить всё
function add_variations_from_acf_fields($post_id) {
// Check if this is a product and we're not in an autosave
if (get_post_type($post_id) !== 'product' || (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)) {
return;
}
// Get the repeater field data
$acf_repeater = get_field('Deelnameprijzen', $post_id);
// Check if there is any data in the repeater field
if ($acf_repeater) {
// Load the product
$product = wc_get_product($post_id);
// Delete existing variations
if ($product->is_type('variable')) {
$existing_variations = $product->get_children();
foreach ($existing_variations as $variation_id) {
wp_delete_post($variation_id, true);
}
} else {
// If the product is not already a variable product, change its type
wp_set_object_terms($post_id, 'variable', 'product_type');
$product = wc_get_product($post_id);
}
// Prepare attributes
$distances = array();
foreach ($acf_repeater as $repeater_item) {
$distances[] = $repeater_item['aantal_kms'];
}
// Ensure distances are unique and filter out any unexpected data
$distances = array_unique(array_filter($distances));
// Set the 'Aantal Kms' attribute
$product_attributes = array();
$product_attributes['pa_aantal_kms'] = array(
'name' => 'Aantal Kms',
'value' => implode(' | ', $distances),
'position' => 0,
'is_visible' => 1,
'is_variation' => 1,
'is_taxonomy' => 0
);
update_post_meta($post_id, '_product_attributes', $product_attributes);
// Create new variations based on the repeater field data
foreach ($acf_repeater as $repeater_item) {
$variation = new WC_Product_Variation();
$variation->set_parent_id($post_id);
// Set variation attributes
$variation_attributes = array(
'pa_aantal_kms' => $repeater_item['aantal_kms']
);
$variation->set_attributes($variation_attributes);
// Set variation price
$variation->set_regular_price($repeater_item['prijs']);
// Save the variation
$variation->save();
}
}
}
add_action('save_post', 'add_variations_from_acf_fields', 10, 1);
Термины создаются, если они не существуют.
Значения атрибутов устанавливаются для каждого варианта.< /п>
Подробнее здесь: https://stackoverflow.com/questions/788 ... s-based-on