我想在 WordPress 中发表一篇带有照片的帖子,但它给出了错误
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
url = 'http://my_website.blog/xmlrpc.php'
username = 'MY_username'
password = 'MY_password'
def send_post(title,content,url_image):
client = Client(url, username, password)
post = WordPressPost()
post.title = title
post.content = content
post.post_status = 'publish'
post.slug = ''
post.thumbnail = url_image
client.call(NewPost(post))
一切正常,但图片不正常 它给了我这个错误
xmlrpc.client.Fault: <Fault 404: '\u0634\u0646\u0627\u0633\u0647\u0654
\u067e\u06cc\u0648\u0633\u062a \u0646\u0627\u0645\u0639\u062a\u0628\u0631
\u0627\u0633\u062a.'>
问题可能出在您设置缩略图的方式上。
post.thumbnail
需要附件帖子的 ID,而不是直接的 URL。要设置帖子的缩略图,您首先必须将图像上传到 WordPress 并获取附件 ID。
from wordpress_xmlrpc.methods.media import UploadFile
from wordpress_xmlrpc import Client
# Your credentials
url = 'http://my_website.blog/xmlrpc.php'
username = 'MY_username'
password = 'MY_password'
client = Client(url, username, password)
# Define your image and its properties
data = {
'name': 'filename.jpg',
'type': 'image/jpeg', # mimetype
}
# Read the binary file and let the XMLRPC library encode it into base64
with open('path_to_your_image.jpg', 'rb') as img:
data['bits'] = img.read()
response = client.call(UploadFile(data))
attachment_id = response['id']
现在您有了
attachment_id
,您可以将其用作帖子的缩略图
from wordpress_xmlrpc import WordPressPost
from wordpress_xmlrpc.methods.posts import NewPost
def send_post(title, content, attachment_id):
post = WordPressPost()
post.title = title
post.content = content
post.post_status = 'publish'
post.thumbnail = attachment_id
post_id = client.call(NewPost(post))
# Call the function
send_post("Your Title", "Your Content", attachment_id)