使用wp_insert_post()时,如何通过图像URL设置特色图像(缩略图)?
5 个回答
- 投票数
-
- 2012-02-05
当图像在媒体库中时,可以将其设置为帖子缩略图.要将图像添加到媒体库中,您需要将其上传到服务器. WordPress已经具有将图像放入媒体库的功能,您只需要一个上传文件的脚本即可.
用法:
Generate_Featured_Image( '../wp-content/my_image.jpg', $post_id ); // $post_id is Numeric ID... You can also get the ID with: wp_insert_post()
功能:
function Generate_Featured_Image( $image_url, $post_id ){ $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $filename = basename($image_url); if(wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename; else $file = $upload_dir['basedir'] . '/' . $filename; file_put_contents($file, $image_data); $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); $res1= wp_update_attachment_metadata( $attach_id, $attach_data ); $res2= set_post_thumbnail( $post_id, $attach_id ); }
http://codex.wordpress.org/Function_Reference/wp_upload_dir
http://codex.wordpress.org/Function_Reference/wp_insert_attachment
编辑: 添加了路径创建
You can set an image as post thumbnail when it is in your media library. To add an image in your media library you need to upload it to your server. WordPress already has a function for putting images in your media library, you only need a script that uploads your file.
Usage:
Generate_Featured_Image( '../wp-content/my_image.jpg', $post_id ); // $post_id is Numeric ID... You can also get the ID with: wp_insert_post()
Function:
function Generate_Featured_Image( $image_url, $post_id ){ $upload_dir = wp_upload_dir(); $image_data = file_get_contents($image_url); $filename = basename($image_url); if(wp_mkdir_p($upload_dir['path'])) $file = $upload_dir['path'] . '/' . $filename; else $file = $upload_dir['basedir'] . '/' . $filename; file_put_contents($file, $image_data); $wp_filetype = wp_check_filetype($filename, null ); $attachment = array( 'post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit' ); $attach_id = wp_insert_attachment( $attachment, $file, $post_id ); require_once(ABSPATH . 'wp-admin/includes/image.php'); $attach_data = wp_generate_attachment_metadata( $attach_id, $file ); $res1= wp_update_attachment_metadata( $attach_id, $attach_data ); $res2= set_post_thumbnail( $post_id, $attach_id ); }
http://codex.wordpress.org/Function_Reference/wp_upload_dir
http://codex.wordpress.org/Function_Reference/wp_insert_attachment
EDIT: Added path creation
-
感谢你付出的努力!但是,这仅在使用$ upload_dir ['basedir'](而不是路径)时有效,因为当我通过postedit界面检查附件时,它被称为.../uploads/FILENAME.EXT,而$ upload_dir ['path']会将其存储在.../uploads/2012/02/FILENAME.EXT之类的文件中. 以某种方式更改文件引用的方式可能更好,但是我不知道如何.Thank you for your efforts! This only works when using $upload_dir['basedir'] (rather than path) though, because when I inspect the attachment through the post edit interface it is referenced as .../uploads/FILENAME.EXT while $upload_dir['path'] would store it in something like .../uploads/2012/02/FILENAME.EXT. It might be even better to somehow change how the file is referenced, but I wouldn't know how.
- 0
- 2012-02-06
- Chris
-
在我的答案中添加了路径创建.Added path creation in my answer.
- 1
- 2012-02-06
- Rob Vermeer
-
感谢您的快速反应:).但是我仍然得到相同的结果,这是显示我的问题的屏幕截图:http://i.imgur.com/iKTNs.png.上半部分是在条件中放置回显的结果,以了解发生了什么.Appreciate your quick response :). I still get the same result however, here's a screenshot displaying my problem: http://i.imgur.com/iKTNs.png . The upper section is the result of placing an echo in your conditional, just to see what's going on.
- 0
- 2012-02-06
- Chris
-
再次更改它,没有将完整路径传递给wp_insert_attachment和wp_generate_attachment_metadata.希望这能解决问题.Changed it again, didn't pass the full path to wp_insert_attachment and wp_generate_attachment_metadata. Hope this will solve the problem.
- 0
- 2012-02-06
- Rob Vermeer
-
完美无瑕,非常感谢!这也解决了大小调整问题,这显然是由错误的路径引起的(即使图像会显示出来).再好不过了!Works flawlessly, thank you so much! This has also fixed a sizing issue, which was apparently caused by incorrect paths (even though the image would show up). Couldn't be any better!
- 0
- 2012-02-06
- Chris
-
感谢您的出色代码.只需要进行一项修改就可以将其与我的CSV导入配合使用,并且将postid放在文件名的前面,以确保图像文件保持唯一.Thanks for your great code. Only one amendment was needed to get it to work with my CSV import and that was prepending the postid to the filename to ensure the image files remain unique.
- 0
- 2012-12-07
- Dave Hilditch
-
让我也赞美一下.喜欢这段代码.感谢您为我节省时间!Let me also heap on the praise. Love this snippet of code. Thanks for saving me hours!
- 0
- 2013-02-11
- bkwdesign
-
只想知道:这样安全吗?是否存在伪装图像的风险,或者wp_check_filetype()会解决这个问题?Just wondering: Is this safe? Is there a risk of someone disguising an image, or does wp_check_filetype() take care of that?
- 0
- 2015-02-14
- LOLapalooza
-
我使用了上面的代码,并对其进行了稍加修改,以获取具有特色的图像,这些图像被称为帖子子弹(如果您运行数千篇文章,这将非常耗时): 代码I used the code above and slightly amended to get featured images which are named as the post slug (which is quite time consuming if you run thousands of posts): `code`
- 0
- 2017-01-19
- Traveler
-
如果在`php.ini`中禁用了`allow_url_fopen`,则无法使用带有URL的`file_get_contents`--[`wp_remote_get]](https://codex.wordpress.org/Function_Reference/wp_remote_get)在各个版本之间都将具有更高的兼容性不同的WP环境usage of `file_get_contents` with a URL will not work if `allow_url_fopen` is disabled in `php.ini` - [`wp_remote_get`](https://codex.wordpress.org/Function_Reference/wp_remote_get) will be more highly compatible across different WP environments
- 0
- 2017-02-24
- highvolt
-
警告:如果文件名称相同,请注意此答案将重写文件.它应使用$post_id或至少uniqid()生成名称Warning: This answer rewrites the file if it has the same name, beware. It should generate names using $post_id or at least uniqid()
- 1
- 2017-05-31
- Ivan Castellanos
-
当我使用它时,在"上传"中创建的图像的文件大小为零.When I use this, the images created in "uploads" have a file size of zero.
- 0
- 2018-03-23
- PJ Brunet
-
- 2016-03-02
我想通过使用WP核心功能来改善Robs答案
download_url
和media_handle_sideload
<?php /** * Downloads an image from the specified URL and attaches it to a post as a post thumbnail. * * @param string $file The URL of the image to download. * @param int $post_id The post ID the post thumbnail is to be associated with. * @param string $desc Optional. Description of the image. * @return string|WP_Error Attachment ID, WP_Error object otherwise. */ function Generate_Featured_Image( $file, $post_id, $desc ){ // Set variables for storage, fix file filename for query strings. preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches ); if ( ! $matches ) { return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) ); } $file_array = array(); $file_array['name'] = basename( $matches[0] ); // Download file to temp location. $file_array['tmp_name'] = download_url( $file ); // If error storing temporarily, return the error. if ( is_wp_error( $file_array['tmp_name'] ) ) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload( $file_array, $post_id, $desc ); // If error storing permanently, unlink. if ( is_wp_error( $id ) ) { @unlink( $file_array['tmp_name'] ); return $id; } return set_post_thumbnail( $post_id, $id ); }
I'd like to improve Robs answer by utilizing the WP core functions
download_url
andmedia_handle_sideload
<?php /** * Downloads an image from the specified URL and attaches it to a post as a post thumbnail. * * @param string $file The URL of the image to download. * @param int $post_id The post ID the post thumbnail is to be associated with. * @param string $desc Optional. Description of the image. * @return string|WP_Error Attachment ID, WP_Error object otherwise. */ function Generate_Featured_Image( $file, $post_id, $desc ){ // Set variables for storage, fix file filename for query strings. preg_match( '/[^\?]+\.(jpe?g|jpe|gif|png)\b/i', $file, $matches ); if ( ! $matches ) { return new WP_Error( 'image_sideload_failed', __( 'Invalid image URL' ) ); } $file_array = array(); $file_array['name'] = basename( $matches[0] ); // Download file to temp location. $file_array['tmp_name'] = download_url( $file ); // If error storing temporarily, return the error. if ( is_wp_error( $file_array['tmp_name'] ) ) { return $file_array['tmp_name']; } // Do the validation and storage stuff. $id = media_handle_sideload( $file_array, $post_id, $desc ); // If error storing permanently, unlink. if ( is_wp_error( $id ) ) { @unlink( $file_array['tmp_name'] ); return $id; } return set_post_thumbnail( $post_id, $id ); }
-
最好使用WordPress本机函数,谢谢.Using the WordPress native functions are the best practice, Thank you.
- 1
- 2018-09-15
- Mostafa Soufi
-
由于某种原因,此版本使我出现错误,提示"未提供有效的URL".,而[Rob Vermeer的答案](https://wordpress.stackexchange.com/a/41300/122391)起作用了.For some reason, this version gave me errors saying "A valid URL was not provided." , whereas [Rob Vermeer's answer](https://wordpress.stackexchange.com/a/41300/122391) worked.
- 0
- 2019-08-28
- Flimm
-
- 2012-01-26
尝试使用
set_post_thumbnail()
.Otto编辑:您已澄清您的问题,因此我将澄清Chip给予的答复.
基本上,您还需要为帖子添加"附件".当图像上传到WordPress媒体库中时,会为其添加一个特殊的帖子条目,并带有附件的帖子类型.该附件通过post_parent标识符链接到某些特定的帖子.
因此,如果您知道附件的ID,则使用发布对象或ID和附件ID调用set_post_thumbnail只需设置发布缩略图标志.
如果尚未创建附件,则需要先执行该操作.最简单的方法是使用
wp_insert_attachment()
.此函数采用一些参数组成的数组,文件名(文件必须已经在正确的上载目录中)以及要将附件附加到的父帖子的帖子ID.仅将文件上传并附加到帖子不会自动执行任何操作.这只是一种分类机制.例如,画廊机制使用帖子的附加图像来构建该帖子的[图库].帖子的缩略图只是已设置为缩略图的附件图像之一.
有关如何使用wp_insert_attachment的更多信息,请参见法典(上面链接).
Try using
set_post_thumbnail()
.Edit by Otto: You clarified your question, so I'll clarify the response Chip gave.
Basically, you need to make the 'attachment' for the post as well. When an image is uploaded into the WordPress media library, a special post entry is made for it with a post type of attachment. This attachment is linked to some specific post via the post_parent identifier.
So if you know the ID of the attachment, then calling set_post_thumbnail with the post object or ID and the attachment ID will simply set the post thumbnail flag.
If you have not created the attachment yet, then you will need to do that first. Easiest way to do that is with
wp_insert_attachment()
. This function takes an array of a few parameters, the filename (the file must already be in the proper uploads directory), and the post ID of the parent post that you want to attach the attachment to.Just having a file uploaded and attached to a post doesn't do anything automatically. This is simply a sort of categorization mechanism. The gallery mechanism, for example, uses the attached images of a post to build the [gallery] for that post. A thumbnail for a post is just one of the attached images which has be set to be the thumbnail.
More info on how to use wp_insert_attachment can be found in the codex (linked above).
-
谢谢您的回复!但是,我将如何检索缩略图ID?我从图像URL开始,所以我想我应该使用其他功能以某种方式将图像添加到wordpress库中吗?Thank you for your reply! How would I retrieve the thumbnail ID, though? I'm starting out with an image URL, so I guess I should somehow add an image to the wordpress library using another function?
- 0
- 2012-01-27
- Chris
-
由于您已经"插入"帖子,因此我假设您已经"将图片"附加到要插入的帖子中.这不是一个有效的假设吗?As you are already *inserting* a post, I had assumed that you were already *attaching images* to the post you're inserting. Is that not a valid assumption?
- 0
- 2012-01-27
- Chip Bennett
-
抱歉,但是我还没有找到如何通过URL将图像实际附加到帖子上的方法.另外,我不希望图像实际显示在帖子本身中.我目前正在寻找将返回$thumbnail_id的函数,并认为wp_insert_attachment()可能会起作用,直到我注意到它已经要求附件位于上传目录中为止.我不知道如何通过其URL获取图像文件,而且我不确定这是否就是我首先要查找的功能.感谢您的帮助!Sorry, but I have not yet found out how to actually attach images to a post by URL. Also, I would not want the image to actually be displayed in the post itself. I'm currently looking for the function which will return the $thumbnail_id, and thought that maybe wp_insert_attachment() would work, until I noticed it already required the attachment to be in the upload directory. I don't know how to get an image file there by its URL, and I'm not sure whether this is the function I'm looking for in the first place. Thank you for your help!
- 0
- 2012-01-27
- Chris
-
您能否用此信息"重写您的问题"以更好地描述您要完成的工作?(或者,保持原样,然后提出一个新问题,询问在插入帖子时如何获取附件ID?)Can you please **rewrite your question** with this information, to better-describe what you're trying to accomplish? (Or, leave this one as-is, and start a new question, to ask how to get the attachment ID when inserting a post?)
- 0
- 2012-01-27
- Chip Bennett
-
原始问题已被编辑,部分已重新措辞,请返回:).The original question has been edited and partly rephrased, please check back :).
- 0
- 2012-01-27
- Chris
-
- 2012-02-06
set_post_thumbnail()
是满足此要求的最佳功能.我认为,您可以通过
get_children()
<找到附件的ID/a>或get_posts()
.结果有一个数组,该数组内部是ID.以下示例进行测试;我希望它能起作用;无需测试即可写作,只能从头开始.对于您的要求,重要的是,您要使用
post-ID
更改post-ID
;返回附件的ID,这样您就可以使用set_post_thumbnail()
.$attachments = get_children( array( 'post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image' ) ); foreach ( $attachments as $attachment_id => $attachment ) { echo wp_get_attachment_image($attachment_id); }
set_post_thumbnail()
is the best function for this requirement.I think, you find the ID of an attachment via
get_children()
orget_posts()
. The result have an array and inside this array is the ID. The follow example for testing; i hope it works; write without tests, only on scratch.For your requirement it is important, that you change
get_the_ID()
with yourpost-ID
; return the ID of the Attachment and this can you use fothset_post_thumbnail()
.$attachments = get_children( array( 'post_parent' => get_the_ID(), 'post_type' => 'attachment', 'post_mime_type' => 'image' ) ); foreach ( $attachments as $attachment_id => $attachment ) { echo wp_get_attachment_image($attachment_id); }
-
- 2015-02-20
只是发现了这一点,并使其变得更加简单,有效,但我不是安全检查器
if(!empty($_FILES)){ require_once( ABSPATH . 'wp-admin/includes/post.php' ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $post_ID = "your post id!"; $attachment_id = media_handle_upload( 'file', $post_ID ); set_post_thumbnail( $post_ID, $attachment_id ); }
简单还是什么?获取正确的文件后,wordpress将处理媒体并上传,然后将其设置为缩略图.
Just found this and made it much simpler, works but I'm no security scrubber
if(!empty($_FILES)){ require_once( ABSPATH . 'wp-admin/includes/post.php' ); require_once( ABSPATH . 'wp-admin/includes/image.php' ); require_once( ABSPATH . 'wp-admin/includes/file.php' ); require_once( ABSPATH . 'wp-admin/includes/media.php' ); $post_ID = "your post id!"; $attachment_id = media_handle_upload( 'file', $post_ID ); set_post_thumbnail( $post_ID, $attachment_id ); }
simple or what? after getting the right files, wordpress will handle the media and upload it, then set it as a thumbnail.
在浏览 wp_insert_post()的函数参考条目时,我注意到数组中不需要参数这样我就可以为帖子设置"特色图片",并在主题中显示为帖子缩略图.
正如Bennett先生所建议的,我已经研究过 set_post_thumbnail()之类的函数,但这似乎是一个WordPress本身和WordPress Codex相对较新的功能.因此,没有任何资料可以解释如何获取和提供$thumbnail_id参数.如果这确实是要使用的函数,当我只有图像URL时,可以通过什么方式为它提供有效的$thumbnail_id参数?
谢谢!