Wordpress功能上传图片并设置为特色图片

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Wordpress功能上传图片并设置为特色图片相关的知识,希望对你有一定的参考价值。

A function to upload an image to the media library and set it as featured image of a post. It requires 2 params. The name of the upload field and of course the post ID.

This function is part of the WPelements library class available on Github. Feedback / suggestions / improvements are always welcome.
  1. /**
  2. * Function to upload an image to the media library and set it as the featured image of a post
  3. * @param string Name of the upload field
  4. * @param int ID of the post
  5. * @return string
  6. * */
  7. public function set_featured_image($file, $post_id){
  8. require_once(ABSPATH . "wp-admin" . '/includes/image.php');
  9. require_once(ABSPATH . "wp-admin" . '/includes/file.php');
  10. require_once(ABSPATH . "wp-admin" . '/includes/media.php');
  11. $attachment_id = media_handle_upload($file, $post_id);
  12. update_post_meta($post_id, '_thumbnail_id', $attachment_id);
  13. $attachment_data = array(
  14. 'ID' => $attachment_id
  15. );
  16. wp_update_post($attachment_data);
  17. return $attachment_id;
  18. }

以上是关于Wordpress功能上传图片并设置为特色图片的主要内容,如果未能解决你的问题,请参考以下文章

wordpress 媒体库图片无法显示?

Wordpress 和 AJAX - 上传特色图片

Wordpress - 短 mp4 视频而不是特色图片

WordPress |在特色图片上使用 imagehover

如果没有为该帖子设置特色图片,想要更改帖子<h1> 标题的颜色

WordPress 自定义帖子类型前端特色图片提交