Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

id|image
--------
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

share|improve this question
    
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 –  Theodore Oct 18 '13 at 19:10

1 Answer 1

up vote 1 down vote accepted

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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