- если продукт A добавлен в перекрестную/дополнительную продажу продукта B, то и продукт B также должен быть добавлен. автоматически добавляться в перекрестные продажи/дополнительные продажи продукта А.
- если продукт А удален из перекрестных продаж/дополнительных продаж продукта Б, то продукт Б также должен автоматически быть удален из перекрестных продаж продукта А.
add_action('save_post_product', 'auto_link_cross_sells', 20, 2);
function auto_link_cross_sells($post_id, $post) {
// Prevent infinite loop using a transient
if (get_transient('auto_cross_sell_processing')) {
return;
}
// Get the current product's cross-sell IDs
$cross_sell_ids = get_post_meta($post_id, '_crosssell_ids', true);
// If there are no cross-sell IDs, exit the function
if (empty($cross_sell_ids) || !is_array($cross_sell_ids)) {
return;
}
// Set a transient to prevent an infinite loop
set_transient('auto_cross_sell_processing', true, 10);
// Loop through each cross-sell product ID
foreach ($cross_sell_ids as $cross_sell_id) {
// Check if the cross-sell product ID is valid
if (!get_post($cross_sell_id)) {
continue;
}
// Get the existing cross-sell IDs for the cross-sell product
$existing_cross_sells = get_post_meta($cross_sell_id, '_crosssell_ids', true);
if (!is_array($existing_cross_sells)) {
$existing_cross_sells = [];
}
// If the current product is not already a cross-sell of the cross-sell product, add it
if (!in_array($post_id, $existing_cross_sells)) {
$existing_cross_sells[] = $post_id;
update_post_meta($cross_sell_id, '_crosssell_ids', $existing_cross_sells);
}
}
// Remove the transient to allow the function to run again later
delete_transient('auto_cross_sell_processing');
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... et-the-pro
Мобильная версия