How to set image as message display image from php to wordpress?

I would like to set the image as a recognized message image. I found this piece of code in the Wordpress documentation, it saves the image in the download directory, but the image is no longer set as the image with the message image (37 in the code).

Could you take a look? many thanks

<?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
source share
2 answers

, ? . brom , , , the_post_thumbnail( $size, $attr );

+3

:

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

All Articles