我有一个在wordpress中创建atachment(zip文件)的功能。
相关代码如下:
我的问题是:有没有办法在创建新附件之前检查是否存在相同的附件名称(或ID或FILE TYPE)? (在将附件插入数据库之前的意思..)
在我当前状态 - 每次运行此函数时都会创建attachemnts。这意味着它可以创建每个tiem的新附件的DB记录 - 即使真实文件只是一个文件。
$attachment = array(
'guid' => $wp_upload_dir['baseurl'] . _wp_relative_upload_path( $path ),
'post_mime_type' => $wp_filetype['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($path )),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $path , $post_id); // perform the magic
require_once(ABSPATH . 'wp-admin/includes/image.php');
wp_update_attachment_metadata( $attach_id, $attach_data ); // perform the magic II
答案 0 :(得分:2)
关于代码发生位置的更多背景信息将非常有用......
尝试这样的方法来检查附属存在:
global $wpdb;
$title_exists = $wpdb->get_results(
$wpdb->prepare(
"SELECT ID FROM $wpdb->posts
WHERE post_title = '$post->post_title'
AND post_type = 'attachment'"
)
);
更改post_title = '$post->post_title'
以获取您需要的任何支票。