使用查询将图像插入WordPress帖子

时间:2013-10-18 作者:vorillaz

我有一个Wordpress安装,有2000个帖子。此外,在我的数据库的一个单独的表中,我有一组图像路径和图像的文件名,每个图像都根据帖子id分配给Wordpress安装的每个帖子。

“我的图像”表的eg

id|image
--------
1 | img1.png
2 | secondimage.jpg
...
2014| onemoreimage.gif
是否可以执行SQL查询或Wordpress API调用,根据ID将每个图像插入为每篇文章的特色图像?还有,我应该在哪里上传原始图像文件?提前感谢

1 个回复
最合适的回答,由SO网友:Ivan Hanák 整理而成

是的,这是可能的,WordPress没有API,但有一些有用的函数。

我会将所有行加载到数组中,如下所示

$your_table = [\'post_id\' => \'image\', \'post_id\' => \'image\', …]
然后执行foreach循环

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\\u meta”研究here

结束