Отображение 61–72 из 120
Loading
No Products for load
// ✅ Синхронизация товаров
add_action('wp_ajax_keycrm_sync_products', function () {
@set_time_limit(0);
@ini_set('memory_limit', '1024M');
$api_key = get_option('keycrm_api_key', '');
if (empty($api_key)) {
wp_send_json_error(['message' => 'API ключ отсутствует']);
}
$page = max(1, intval($_GET['page'] ?? 1));
$batch_size = max(1, intval($_GET['batch_size'] ?? 20));
$only_new = intval($_GET['only_new'] ?? 0);
$load_outofstock = intval($_GET['load_outofstock'] ?? 0);
$sync_images = intval($_GET['sync_images'] ?? 1);
// --- ЛОГ для отладки
error_log("keycrm_sync_products → page=$page, batch_size=$batch_size, only_new=$only_new, load_outofstock=$load_outofstock, sync_images=$sync_images");
$params = [
'page' => $page,
'limit' => $batch_size,
];
// ❗ Корректная фильтрация остатков
if (!$load_outofstock) {
$params['filters[stock_from]'] = 1; // Только товары с остатком > 0
}
// --- Отправляем запрос в KeyCRM
$response = wp_remote_get('https://openapi.keycrm.app/v1/products?' . http_build_query($params), [
'headers' => [ 'Authorization' => 'Bearer ' . $api_key ]
]);
if (is_wp_error($response)) {
error_log('❌ Ошибка соединения с KeyCRM: ' . $response->get_error_message());
wp_send_json_error(['message' => 'Ошибка соединения с KeyCRM']);
}
$json = json_decode(wp_remote_retrieve_body($response), true);
$products = $json['data'] ?? [];
$result = [];
foreach ($products as $product) {
$sku = $product['sku'] ?? '';
if (!$sku) continue;
// --- Проверяем существование товара по SKU
$existing = wc_get_product_id_by_sku($sku);
if ($only_new && $existing) continue;
$post_id = $existing ?: wp_insert_post([
'post_title' => sanitize_text_field($product['name'] ?? 'Без названия'),
'post_status' => 'publish',
'post_type' => 'product',
]);
if (!$post_id || is_wp_error($post_id)) continue;
// --- Устанавливаем свойства товара
wp_set_object_terms($post_id, 'simple', 'product_type');
update_post_meta($post_id, '_sku', $sku);
update_post_meta($post_id, '_stock', intval($product['quantity'] ?? 0));
update_post_meta($post_id, '_manage_stock', 'yes');
update_post_meta($post_id, '_stock_status', (intval($product['quantity']) > 0) ? 'instock' : 'outofstock');
if (isset($product['price'])) {
update_post_meta($post_id, '_regular_price', floatval($product['price']));
update_post_meta($post_id, '_price', floatval($product['price']));
}
// --- Присваиваем категории по именам
if (!empty($product['categories']) && is_array($product['categories'])) {
$category_names = [];
foreach ($product['categories'] as $cat) {
if (!empty($cat['name'])) {
$category_names[] = sanitize_text_field($cat['name']);
}
}
if (!empty($category_names)) {
$term_ids = [];
foreach ($category_names as $cat_name) {
// Проверяем, есть ли такая категория
$term = term_exists($cat_name, 'product_cat');
if (!$term) {
// Если нет — создаём
$new_term = wp_insert_term($cat_name, 'product_cat');
if (!is_wp_error($new_term)) {
$term_ids[] = $new_term['term_id'];
}
} else {
$term_ids[] = is_array($term) ? $term['term_id'] : $term;
}
}
if (!empty($term_ids)) {
wp_set_post_terms($post_id, $term_ids, 'product_cat');
}
}
}
// --- Обработка изображений
if ($sync_images && !empty($product['images']) && is_array($product['images'])) {
$image_urls = array_filter($product['images'], function ($i) {
return is_string($i) && filter_var($i, FILTER_VALIDATE_URL);
});
if (!empty($image_urls)) {
require_once ABSPATH . 'wp-admin/includes/image.php';
require_once ABSPATH . 'wp-admin/includes/file.php';
require_once ABSPATH . 'wp-admin/includes/media.php';
// Удалим старое изображение, если есть
$old_thumbnail_id = get_post_thumbnail_id($post_id);
if ($old_thumbnail_id) {
wp_delete_attachment($old_thumbnail_id, true);
}
// Загружаем новое изображение
$attach_id = media_sideload_image($image_urls[0], $post_id, null, 'id');
if (!is_wp_error($attach_id)) {
set_post_thumbnail($post_id, $attach_id);
} else {
error_log("❗ Ошибка загрузки изображения для SKU $sku: " . $attach_id->get_error_message());
}
}
}
$result[] = [
'sku' => $sku,
'name' => $product['name'] ?? '',
'stock' => $product['quantity'] ?? 0,
'photos' => count($product['images'] ?? []),
'status' => get_post_status($post_id),
];
}
wp_send_json_success($result);
});
Warning: Cannot modify header information - headers already sent by (output started at /home/pearlstore.uz/public_html/wp-content/plugins/keycrm-stock-sync/includes/ajax-handlers.php:1) in /home/pearlstore.uz/public_html/wp-content/plugins/themeftc-core/redirect.php on line 37