I have a Wordpress installation with 2.000 posts. Also in a separate table of my database I have a set of image paths and the filenames of the images, each image is assigned to each post of my Wordpress installation based on the post id.

eg of my images' table

1 | img1.png
2 | secondimage.jpg
2014| onemoreimage.gif

Is it possible to execute an SQL query or a Wordpress API call to insert each image as featured image of each post based on the ID? Also where should I upload the original image files? Thanks in advance

  • isn't it a sql query like: SELECT * FROM <your table> WHERE id=<$post->ID> what gives you all the images? – philipp Oct 18 '13 at 18:50
  • I dont't have a problem extracting the images but inserting them in the Wordpress db schema – vorillaz Oct 18 '13 at 19:10

Yes, it is possible, WordPress does not have an API, but some useful functions.

I would load all your rows into array like

$your_table = ['post_id' => 'image', 'post_id' => 'image', …]

Then execute a foreach loop

foreach($your_table as $post_id => $image)
    //full path to the image
    $image_path = _YOUR_FULL_ABSOLUTE_PATH.$image;

      * Get an ID of the inserted attachment
      * This takes care of resizing image and stuff…
      * The fourth param I would sugest you to keep true, since in case of duplicate entry in your table, it will not have been inserted more than once
    $featured_image = wp_insert_attachment(array('attachment_meta'), $image_path, $post_id, true);

    //assign featured image
    add_post_meta($post_id, '_thumbnail_id', $featured_image);

'attachment_meta' study here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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