4

我想将图像设置为帖子的特色图像。我在 wordpress 文档中找到了这段代码,它将图像保存在上传目录中,但图像不再设置为帖子的特色图像(代码中的 37)。

你能看看吗?多谢

<?php
  $wp_filetype = wp_check_filetype(basename($filename), null );
  $wp_upload_dir = wp_upload_dir();
  $attachment = array(
     'guid' => $wp_upload_dir['url'] . '/' . basename( $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, 37 );
  // 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 );
?>
4

2 回答 2

3

据我了解,您想在帖子中使用图片作为特色图片吗?那么为什么您不在帖子中使用后端特色图片浏览选项。在那里,您可以简单地将图片上传为特色图片,并且您可以在页面上使用此代码显示该特色图片 the_post_thumbnail( $size, $attr );

于 2013-09-28T08:29:03.333 回答
3

您需要在代码末尾添加以下行:

// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id); 
于 2013-11-24T05:46:02.027 回答