Описание товаров, генерация использую название
function bygi_fill_products_batch() {
$offset = (int) get_option('bygi_product_desc_offset', 0);
$limit = 15;
$min_length = 30;
$products = get_posts([
'post_type' => 'product',
'post_status' => 'publish',
'numberposts' => $limit,
'offset' => $offset,
'orderby' => 'ID',
'order' => 'ASC'
]);
if (empty($products)) {
delete_option('bygi_product_desc_offset');
error_log('bygi: DONE filling descriptions');
return;
}
foreach ($products as $product) {
if (strlen(trim(wp_strip_all_tags($product->post_content))) > $min_length) {
continue;
}
$title = $product->post_title;
$terms = wp_get_post_terms($product->ID, 'product_cat', ['fields' => 'names']);
$category = !empty($terms) ? $terms[0] : '';
$description = bygi_generate_flower_text($title, $category);
wp_update_post([
'ID' => $product->ID,
'post_content' => $description
]);
}
update_option('bygi_product_desc_offset', $offset + $limit);
}
function bygi_parse_flower_title($title) {
$title = mb_strtolower($title);
// извлекаем число (например 45)
preg_match('/(\d+)/u', $title, $countMatch);
$count = $countMatch[1] ?? '';
// убираем число из строки
$name = trim(preg_replace('/\d+/u', '', $title));
// базовая форма
if ($count) {
return "букет из {$count} {$name}";
}
return $title;
}
function bygi_generate_flower_text($title, $category = '') {
$parsed = bygi_parse_flower_title($title);
$variants = [
"{$parsed} — отличный выбор для подарка и особого случая. Композиция собрана из свежих цветов и аккуратно оформлена опытными флористами.",
"{$parsed} подойдёт для дня рождения, свидания или любого важного события. Букет выглядит стильно и передаёт настроение без слов.",
"Вы можете заказать {$parsed} с доставкой. Мы используем только свежие цветы, чтобы букет радовал как можно дольше.",
"{$parsed} — это гармоничное сочетание красоты и свежести. Такой букет станет приятным сюрпризом для близкого человека."
];
if ($category) {
$variants[] = "Товар относится к категории {$category} и пользуется популярностью среди покупателей.";
}
shuffle($variants);
$text = implode(' ', array_slice($variants, 0, 3));
return mb_substr($text, 0, 500);
}
function bygi_test_single_product_description($product_id) {
$product = get_post($product_id);
if (!$product || $product->post_type !== 'product') {
return 'Product not found';
}
// ✅ правильная проверка
if (strlen(trim(wp_strip_all_tags($product->post_content))) > 0) {
return 'Already has description';
}
$title = $product->post_title;
$terms = wp_get_post_terms($product->ID, 'product_cat', ['fields' => 'names']);
$category = !empty($terms) ? $terms[0] : '';
$description = bygi_generate_flower_text($title, $category);
wp_update_post([
'ID' => $product->ID,
'post_content' => $description
]);
return $description;
}
add_action('admin_init', function() {
if (!current_user_can('administrator')) return;
// защита от слишком частого запуска
if (get_transient('bygi_batch_lock')) return;
set_transient('bygi_batch_lock', 1, 10); // 10 секунд блок
bygi_fill_products_batch();
});