1

How do I add a Featured Image programatically, given the URL/filename of the image, and Post ID associated with it?

7
  • Is the image in the media library? Or do you only have a URL? Commented Sep 18, 2018 at 14:53
  • It's not in the media library, I have a local copy inside my theme folder.
    – Pim
    Commented Sep 18, 2018 at 15:01
  • Why the theme folder? Are you trying to set a default placeholder image? Commented Sep 18, 2018 at 16:13
  • Pls. use Google and refer to the Codex: codex.wordpress.org/Function_Reference/wp_insert_attachment
    – Hans
    Commented Sep 18, 2018 at 16:18
  • You have a set of images. And you have a set of posts. You want those images to be added as featured image of its respective post? Automatically? Commented Sep 18, 2018 at 17:17

1 Answer 1

3

For each image/post combination, run the following. $image_name is the filename, $post_id is the post ID.

if( $image_name != '' && !has_post_thumbnail( $post_id ) ){
  $base = get_stylesheet_directory();
  $imgfile= $base . '/import/' . $image_name; // Images are stored inside an imports folder, in the theme directory
  $filename = basename($imgfile);
  $upload_file = wp_upload_bits($filename, null, file_get_contents($imgfile));
  if (!$upload_file['error']) {
    $wp_filetype = wp_check_filetype($filename, null );
    $attachment = array(
      'post_mime_type' => $wp_filetype['type'],
      'post_parent' => 0,
      'post_title' => preg_replace('/\.[^.]+$/', '', $filename),
      'post_content' => '',
      'post_status' => 'inherit'
    );
    $attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $post_id );

    if (!is_wp_error($attachment_id)) {
      require_once(ABSPATH . "wp-admin" . '/includes/image.php');
      $attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
      wp_update_attachment_metadata( $attachment_id,  $attachment_data );
    }
    set_post_thumbnail( $post_id, $attachment_id );

  }
}

If handling a lot of images/posts, you might run into a PHP timeout. If so, simply run the function again. There is a check for images that have already been attached so this shouldn't be a problem.

2
  • Sounds beautiful! Was it tested?
    – Max Yudin
    Commented Oct 17, 2018 at 7:52
  • Yes it was, I ran it on my own site.
    – Pim
    Commented Oct 17, 2018 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.