python - 使用 Python-xmlrpc 从外部图像链接设置 WordPress 帖子缩略图

标签 python python-3.x wordpress python-2.7 wordpress-rest-api

经过大量 Google 搜索后,我来到这里:如何使用来自附件 ID 的外部图像链接设置帖子缩略图?

这是我能找到的所有内容,但是我无法更改它以从外部图像链接设置缩略图。

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost

#authenticate
wp_url = "https://blog.com/xmlrpc.php"
wp_username = "My_User_ID_on_WP"
wp_password = "My_PWD_on_WP"


wp = Client(wp_url, wp_username, wp_password)

#post and activate new post
post = WordPressPost()
post.title = '3 Post'
post.content = '<h1>heading 1</h1>Tayloe was here<br><small>here too!</small><p>New para.'
post.post_status = 'draft'
post.thumbnail = 50  # The ID of the image determined in Step 1
post.slug = "123abc"
post.terms_names = {
  'post_tag': ['MyTag'],
  'category': ['Category']
}
wp.call(NewPost(post))

注意:我不想在我的服务器上保存图像并仅使用外部图像

最佳答案

您可以尝试下载图像,将其上传到您的 Wordpress 站点,然后使用上述 ID 作为缩略图参数:

import base64
import requests

# ...

# raw string url
url = r'https://png.pngtree.com/element_our/20190530/ourmid/pngtree-cartoon-google-icon-download-image_1257171.jpg'

# retrieve and store base64 encoded image and mime-type
r = requests.get(url)
mime_type = r.headers['Content-Type']
img_base64 = base64.b64encode(r.content)

upload_image_dict = {
    'name': 'some_file_name.ext',
    'type': mime_type,
    'bits': img_base64,
    'overwrite': True
}

resp = wordpress_xmlrpc.methods.media.UploadFile(upload_image_dict)

image_id = resp['id']

# ... [ your code here]

post.thumbnail = image_id

# ...

https://python-wordpress-xmlrpc.readthedocs.io/en/latest/ref/methods.html#wordpress_xmlrpc.methods.media.UploadFile

关于python - 使用 Python-xmlrpc 从外部图像链接设置 WordPress 帖子缩略图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59926706/

相关文章:

python - 在Supervisord中通过sh脚本启动程序

python - 如何将字符串的各个部分提取为单独的字符串

python - 二分查找小错误Python 3.5

php - 对于 wordpress 插件,哪个是最好的 mysql 或 mysqli 或 $wpdb

php - 在 WordPress 主题中对帖子进行分页

python - Flask-Sqlalchemy:数据库查询不返回新数据

python - 为什么测试功能看不到我的 py.test 装置?

python - 以特定方式组合数组元素并记录它

python - 导入错误 : cannot import name '_ColumnEntity' from 'sqlalchemy.orm.query'

php - 回复按钮未链接到 URL