如何在Wordpress上使用php将图像设置为帖子的特色图像


how to set an image as featured image of a post with php on Wordpress?

我想将图像设置为帖子的特色图像。我在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 );
?>
您需要

在代码末尾添加以下行:

// add featured image to post
add_post_meta($post_id, '_thumbnail_id', $attach_id); 

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

您可以使用以下函数:

// Set featured image
set_post_thumbnail( $post_id, $image_id );