检查媒体库中是否已存在文件


8

我正在插件中创建自定义文件,并使用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。

谢谢你的帮助。

Answers:


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

您可以在代码顶部使用它。然后检查的值$count。如果为0,则可以继续添加附件


2

我知道这是一个老问题,但是我不喜欢这些答案,因此这是我的解决方案。

这将检查文件是否存在。如果是这样,它将更新现有的附件;如果没有,它将创建一个新的附件。

// Get upload dir
$upload_dir    = wp_upload_dir();
$upload_folder = $upload_dir['path'];

// Set filename, incl path
$filename = "{$upload_folder}/myfile-{$id}.pdf";

// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );

// Get file title
$title = preg_replace( '/\.[^.]+$/', '', basename( $filename ) );

// Prepare an array of post data for the attachment.
$attachment_data = array(
    'guid'           => $upload_dir['url'] . '/' . basename( $filename ),
    'post_mime_type' => $filetype['type'],
    'post_title'     => $title,
    'post_content'   => '',
    'post_status'    => 'inherit'
);

// Does the attachment already exist ?
if( post_exists( $title ) ){
  $attachment = get_page_by_title( $title, OBJECT, 'attachment');
  if( !empty( $attachment ) ){
    $attachment_data['ID'] = $attachment->ID;
  }
}

// If no parent id is set, reset to default(0)
if( empty( $parent_id ) ){
  $parent_id = 0;
}

// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment_data, $filename, $parent_id );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );

在上面的示例中,我在$ filename中使用.pdf,但是您可以将其替换为任何文件名/文件类型。


1

我有这种方法(感谢Mridul):

function MediaFileAlreadyExists($filename){
    global $wpdb;
    $query = "SELECT COUNT(*) FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'";
    return ($wpdb->get_var($query)  > 0) ;
}

// MediaFileAlreadyExists("my-image.png");

0

此函数将媒体文件名作为参数,如果存在则返回meta_id,否则返回(false)。

function MediaFileAlreadyExists($filename){
    global $wpdb;
    $query = "SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_value LIKE '%/$filename'";

    if ( $wpdb->get_var($query) ){
        return $wpdb->get_var($query);
    }

    return false;
}

0

您可以使用检查图像是否存在post_exists($filename)。如果图像存在,您可以对其进行更新也可以创建它

 //if image exist update else create it
        if (post_exists($filename)){
                $page = get_page_by_title($filename, OBJECT, 'attachment');
                $attach_id = $page->ID;

                $attach_data = wp_generate_attachment_metadata( $attach_id, $destination ); // Generate attachment data, filesize, height, width etc.

                wp_update_attachment_metadata( $attach_id, $attach_data ); // Add the above meta data

                add_post_meta($attach_id, '_wp_attachment_image_alt', $filealt); // Add the alt text 
        }
        else{

                $attach_id = wp_insert_attachment( $attachment, $destination, $post_id ); 

                $attach_data = wp_generate_attachment_metadata( $attach_id, $destination ); 

                wp_update_attachment_metadata( $attach_id, $attach_data ); 

                add_post_meta($attach_id, '_wp_attachment_image_alt', $filealt); 
            }

1
您能否在答案中添加有关代码如何工作的解释?
kero
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.