我已经实现了一个前端表单来提交帖子。图像上传由Wordpress媒体库处理
用户单击“上载图像”打开媒体库,用户可以选择现有图像或上载新图像。图像路径(URL)将填充到<input>
字段Problem:我的问题与特色图片有关:如果用户选择existing 媒体库中的图像,此图像已再次添加到媒体库中,我希望避免此操作,原因有两个:
a) 节省磁盘空间
现在我有一张图像保存了两次:http://localhost/?attachment_id=2523
以及http://localhost/images/picture.jpg
避免媒体库中的重复
用户可以从前端访问媒体库,我不希望他们看到重复的图像
Is it possible to assign one image as a featured image to multiple posts?
我得到的是:
// $featuredimg contains the URL to the image: http://mydomain.com/wp-content/uploads...
$filetype = wp_check_filetype( basename( $featuredimg ), null );
$wp_upload_dir = wp_upload_dir();
// Prepare an array of post data for the attachment.
$attachment = array(
\'guid\' => $wp_upload_dir[\'url\'] . \'/\' . basename( $featuredimg ),
\'post_mime_type\' => $filetype[\'type\'],
\'post_title\' => preg_replace( \'/\\.[^.]+$/\', \'\', basename( $featuredimg ) ),
\'post_content\' => \'\',
\'post_status\' => \'inherit\'
);
$thumb_id = wp_insert_attachment( $attachment, $featuredimg, $pid );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $thumb_id, $featuredimg );
wp_update_attachment_metadata( $thumb_id, $attach_data );
update_post_meta( $pid, \'_thumbnail_id\', $thumb_id );
最合适的回答,由SO网友:Hannes 整理而成
我建议您查看$featuredimg URL。如果已经有带有此URL的附件,只需获取ID并调用
update_post_meta( $pid, \'_thumbnail_id\', $thumb_id );
有一个有用的函数可以获取现有URL的ID:
Philip Newcomerfunction pn_get_attachment_id_from_url( $attachment_url = \'\' ) {
global $wpdb;
$attachment_id = false;
// If there is no url, return.
if ( \'\' == $attachment_url )
return;
// Get the upload directory paths
$upload_dir_paths = wp_upload_dir();
// Make sure the upload path base directory exists in the attachment URL, to verify that we\'re working with a media library image
if ( false !== strpos( $attachment_url, $upload_dir_paths[\'baseurl\'] ) ) {
// If this is the URL of an auto-generated thumbnail, get the URL of the original image
$attachment_url = preg_replace( \'/-\\d+x\\d+(?=\\.(jpg|jpeg|png|gif)$)/i\', \'\', $attachment_url );
// Remove the upload path base directory from the attachment URL
$attachment_url = str_replace( $upload_dir_paths[\'baseurl\'] . \'/\', \'\', $attachment_url );
// Finally, run a custom database query to get the attachment ID from the modified attachment URL
$attachment_id = $wpdb->get_var( $wpdb->prepare( "SELECT wposts.ID FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta WHERE wposts.ID = wpostmeta.post_id AND wpostmeta.meta_key = \'_wp_attached_file\' AND wpostmeta.meta_value = \'%s\' AND wposts.post_type = \'attachment\'", $attachment_url ) );
}
return $attachment_id;
}