問題描述

我在插件中創建自定義文件,並使用 Wordpress Codex 中為 wp_insert_attachment 提供的代碼將其添加到媒體庫。但是,我的插件偶爾會覆蓋這些文件。我需要確保這些文件不再添加到媒體庫。這是當前的代碼:

$wp_filetype = wp_check_filetype(basename($filename), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
   'guid' => $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path( $filename ),
   'post_mime_type' => $wp_filetype['type'],
   'post_title' => preg_replace('/.[^.]+$/', '', basename($filename)),
   'post_content' => '',
   'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename);
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

我只需要檢查該文件是否已經是媒體庫的一部分,如果它是更新。我沒有一個 post_id 可以使用,只是永久鏈接和 guid 。

謝謝你的幫助。

最佳解決方案

global $wpdb;
$image_src = $wp_upload_dir['baseurl'] . '/' . _wp_relative_upload_path( $filename );
$query = "SELECT COUNT(*) FROM {$wpdb->posts} WHERE guid='$image_src'";
$count = $wpdb->get_var($query);

您可以在代碼的頂部使用它。然後檢查 $count 的值。如果為 0,則可以繼續添加附件

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。