python+wordpress_xmlrpc:画像アップロード
新規画像アップロード
[code lang=”python”]
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import media, posts
client = Client(‘http://xxxxxx.net/xxxxxx/xmlrpc.php’,’ユーザーネーム’,’パスワード’)
filename = ‘/home/user/xxx.png’ #画像のパス
data = {
‘name’: ‘picture.jpg’,
‘type’: ‘image/jpeg’,
}
with open(filename, ‘rb’) as img:
data[‘bits’] = xmlrpc_client.Binary(img.read())
response = client.call(media.UploadFile(data))
attachment_id = response[‘id’] #attachment_idの設定
[/code]
attachment_idは普通に画像をアップロードした時にも画像に対して付与されます
VPSから記事を投稿する際のサムネイル画像の設定
[code lang=”python”]
#coding: utf-8
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
wp = Client(‘http://xxxxxx.net/xxxxxx/xmlrpc.php’,’ユーザーネーム’,’パスワード’)
post = WordPressPost()
def post_contents():
post.title = ‘title’
post.content = ‘content’
post.terms_names = {‘category’: [‘category’]}
post.post_status = ‘publish’
post.thumbnail = xxx #サムネイルにする画像のattachment_idを入れる
wp.call(NewPost(post))
[/code]
attachment_idの確認方法
投稿記事中に画像ファイルを追加すると、下記の様にコードが追加されます
<img src=”http://xxxxxx.net/xxxxxx/wp-content/uploads/2015/01/xxxxxx_400x400-e111111111111-300×237.jpg” alt=”” width=”300″ height=”237″ class=”alignnone size-medium wp-image-212″ />
最後の数字(上記の場合212)が、その画像のattachment_idです。
参考