Плотоядные растения дома: виды, уход и секреты содержания
Хотите завести дома экзотическое хищное растение? Узнайте, какие виды выбрать, как правильно ухаживать за мухоловкой или росянкой и создать для них идеальные условия.
private function set_as_featured_image(int $post_id, string $image_url, string $image_alt = ''): array { global $wpdb; // Глобальная переменная для работы с базой данных require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); $this->logger->debug('set_as_featured_image started', ['post_id' => $post_id, 'url' => $image_url]); // 1. Попробуем найти ID вложения по URL. $attachment_id = attachment_url_to_postid($image_url); // If not found by URL, try to find by filename (more reliable for existing uploads) if (!$attachment_id) { $filename = basename(parse_url($image_url, PHP_URL_PATH)); $attachment_id = $this->find_attachment_by_filename($filename); if ($attachment_id) { $this->add_detailed_log('Found existing attachment by filename.', ['filename' => $filename, 'attachment_id' => $attachment_id]); } } if ($attachment_id) { // Изображение найдено в медиатеке, используем его ID $this->add_detailed_log('Image already in media library.', ['url' => $image_url, 'attachment_id' => $attachment_id]); $this->logger->debug('Found existing attachment for the URL.', ['url' => $image_url, 'attachment_id' => $attachment_id]); // Проверяем, прикреплено ли изображение к посту. Если нет, прикрепляем. if ($post_id !== (int) get_post_field('post_parent', $attachment_id)) { wp_update_post([ 'ID' => $attachment_id, 'post_parent' => $post_id, ]); $this->add_detailed_log('Attached existing image to the post.', ['attachment_id' => $attachment_id, 'post_id' => $post_id]); $this->logger->info('Attached existing image to the post.', ['attachment_id' => $attachment_id, 'post_id' => $post_id]); } } else { // Изображение не найдено в медиатеке, значит, оно внешнее. Загружаем его. $this->add_detailed_log('Image not found in media library. Assuming it is external and uploading.', ['url' => $image_url]); $this->logger->debug('Image not found in media library. Assuming it is external and uploading.', ['url' => $image_url]); $attachment_id = $this->upload_image_to_media_library($post_id, $image_url, $image_alt); } if (!$attachment_id) { $error_msg = 'Could not get an attachment ID for the image (either by finding or uploading).'; $this->add_detailed_log($error_msg, ['post_id' => $post_id, 'url' => $image_url]); $this->logger->warning($error_msg, ['post_id' => $post_id, 'url' => $image_url]); return ['success' => false, 'message' => $error_msg]; } // 2. Проверим, не установлено ли это изображение уже как миниатюра. Обновим кэш перед проверкой. $this->logger->debug('Pre-setting checks.', ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'current_thumbnail_id_before_flush' => get_post_thumbnail_id($post_id)]); clean_post_cache($post_id); wp_update_post(['ID' => $post_id]); // Это может помочь синхронизировать кэш. $current_thumbnail_id = get_post_thumbnail_id($post_id); $current_thumbnail_id_from_db = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_thumbnail_id'", $post_id)); $this->logger->debug('Post cache flushed and post updated. Checking thumbnail ID.', [ 'post_id' => $post_id, 'attachment_id' => $attachment_id, 'current_thumbnail_id_cached' => $current_thumbnail_id, 'current_thumbnail_id_from_db' => $current_thumbnail_id_from_db ]); if ($current_thumbnail_id == $attachment_id) { $msg = 'This image is already the featured image for this post (based on cached get_post_thumbnail_id).'; $this->add_detailed_log($msg, ['attachment_id' => $attachment_id, 'current_id_cached' => $current_thumbnail_id, 'current_id_db' => $current_thumbnail_id_from_db]); $this->logger->info($msg, ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'current_id_cached' => $current_thumbnail_id, 'current_id_db' => $current_thumbnail_id_from_db]); return ['success' => true, 'attachment_id' => $attachment_id, 'message' => $msg]; } elseif ($current_thumbnail_id_from_db == $attachment_id) { $msg = 'This image is already the featured image for this post (based on direct DB query).'; $this->add_detailed_log($msg, ['attachment_id' => $attachment_id, 'current_id_cached' => $current_thumbnail_id, 'current_id_db' => $current_thumbnail_id_from_db]); $this->logger->info($msg, ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'current_id_cached' => $current_thumbnail_id, 'current_id_db' => $current_thumbnail_id_from_db]); return ['success' => true, 'attachment_id' => $attachment_id, 'message' => $msg]; } else { $this->add_detailed_log('Current thumbnail ID does not match the target attachment ID (cached or DB).', [ 'current_thumbnail_id_cached' => $current_thumbnail_id, 'current_thumbnail_id_db' => $current_thumbnail_id_from_db, 'target_attachment_id' => $attachment_id ]); } // 3. Устанавливаем как featured image $this->add_detailed_log('Attempting to set post thumbnail via set_post_thumbnail.', ['attachment_id' => $attachment_id]); $result = set_post_thumbnail($post_id, $attachment_id); if ($result) { $this->add_detailed_log('Featured image set successfully.'); $this->logger->info('Featured image set successfully', ['post_id' => $post_id, 'attachment_id' => $attachment_id]); return ['success' => true, 'attachment_id' => $attachment_id, 'message' => 'Featured image set successfully via set_post_thumbnail.']; } else { // set_post_thumbnail не сработал. Попробуем напрямую через update_post_meta. $this->add_detailed_log('set_post_thumbnail failed, attempting to set via update_post_meta.', ['attachment_id' => $attachment_id]); $meta_update_result = update_post_meta($post_id, '_thumbnail_id', $attachment_id); if ($meta_update_result !== false) { // update_post_meta возвращает false, если значение не изменилось или при ошибке. // Принудительно удаляем кэш мета-данных поста, чтобы WordPress точно перечитал из базы. wp_cache_delete($post_id, 'post_meta'); // Проверим результат напрямую из базы данных. $db_thumbnail_id = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_thumbnail_id'", $post_id)); if ((int)$db_thumbnail_id === (int)$attachment_id) { $msg = 'Featured image set successfully via update_post_meta (confirmed by direct DB query).'; $this->add_detailed_log($msg, ['attachment_id' => $attachment_id, 'db_thumbnail_id' => $db_thumbnail_id]); $this->logger->info($msg, ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'db_thumbnail_id' => $db_thumbnail_id]); return ['success' => true, 'attachment_id' => $attachment_id, 'message' => $msg]; } else { $error_msg = 'update_post_meta reported success, but direct DB query shows a different _thumbnail_id.'; $this->add_detailed_log($error_msg, ['attachment_id' => $attachment_id, 'db_thumbnail_id' => $db_thumbnail_id]); $this->logger->error($error_msg, ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'db_thumbnail_id' => $db_thumbnail_id]); return ['success' => false, 'message' => $error_msg]; } } else { // update_post_meta вернул false. // Проверим, возможно, оно уже было установлено, но кэш был неактуален. // Принудительно удаляем кэш мета-данных поста. wp_cache_delete($post_id, 'post_meta'); $final_check_thumbnail_id = get_post_thumbnail_id($post_id); $final_db_thumbnail_id = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key = '_thumbnail_id'", $post_id)); if ((int)$final_check_thumbnail_id === (int)$attachment_id || (int)$final_db_thumbnail_id === (int)$attachment_id) { $msg = 'Featured image was apparently already set (confirmed by cache flush and direct DB query).'; $this->add_detailed_log($msg, ['attachment_id' => $attachment_id, 'cached_id' => $final_check_thumbnail_id, 'db_id' => $final_db_thumbnail_id]); $this->logger->info($msg, ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'cached_id' => $final_check_thumbnail_id, 'db_id' => $final_db_thumbnail_id]); return ['success' => true, 'attachment_id' => $attachment_id, 'message' => $msg]; } else { $error_msg = 'Both set_post_thumbnail and update_post_meta failed to set the featured image.'; $this->add_detailed_log($error_msg, ['attachment_id' => $attachment_id, 'cached_id' => $final_check_thumbnail_id, 'db_id' => $final_db_thumbnail_id]); $this->logger->error($error_msg, ['post_id' => $post_id, 'attachment_id' => $attachment_id, 'cached_id' => $final_check_thumbnail_id, 'db_id' => $final_db_thumbnail_id]); return ['success' => false, 'message' => $error_msg]; } } } }
Хотите завести дома экзотическое хищное растение? Узнайте, какие виды выбрать, как правильно ухаживать за мухоловкой или росянкой и создать для них идеальные условия.