dongrao1862 2019-06-10 19:00
浏览 244
已采纳

如何批量设置导入的WordPress帖子的缩略图

I scrape data from a website and store it into an XML file (using python). While downloading images from other website and storing them into my WordPress site, the WordPress assign them a unique ID which I don't know. So I can't assign that image as a thumbnail to my scraped posts. I can't edit posts one by one because they are in bulk. Is there any other solution?

I can display images on posts but I need to know the ID to assign them as a thumbnail. I also used plugins which auto assign the first image as a thumbnail but they also require image ID...

  • 写回答

1条回答 默认 最新

  • dongnao3990 2019-06-10 21:44
    关注

    Possible duplicate of this question. You need to use a variety of built-in WordPress functions for this:

    wp_insert_attachment()
    set_post_thumbnail()
    wp_generate_attachment_metadata()
    wp_update_attachment_metadata()
    

    wp_insert_attachment() is probably your most important function as it returns your attachment (image) ID. set_post_thumbnail() then takes this attachment ID and your post ID to set the image as the featured image in the post.

    When I've done this in the past I also found that I had to use the metadata functions above to correctly assign the image which from memory was for removing posts from an import and their associated images. For a complete example for this see here

            file_put_contents($oldfile, $image_data);
            rename( $oldfile, $newfile );
    
            $wp_filetype = wp_check_filetype($filename, null );
            $attachment = array(
                'post_mime_type' => $wp_filetype['type'],
                'post_title' => sanitize_file_name($filename),
                'post_content' => '',
                'post_status' => 'inherit'
            );
    
            $attach_id = wp_insert_attachment( $attachment, $newfile, $post_id );
    
            if ( $set_thumb ) {
                $res2= set_post_thumbnail( $post_id, $attach_id );
            }
    
            $attach_data = wp_generate_attachment_metadata( $attach_id, $newfile );
            $update_attach_metadata = wp_update_attachment_metadata( $attach_id, $attach_data );
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部