When writing a blog article with WordPress, it is a memorandum that I checked if I could post an article with an image from Python as it is by inserting a graph aggregated with Python.
It seems that there are two types of methods, but here I used Python-wordpress-xmlrpc.
$python -V
Python 3.8.3
Install python-wordpress-xmlrpc with pip. I'm using Anaconda, so I originally wanted to install it with conda, but I couldn't find it.
pip install python-wordpress-xmlrpc
# import
import os
from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods import media
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.methods.users import GetUserInfo
def upload_image(in_image_file_name, out_image_file_name):
if os.path.exists(in_image_file_name):
with open(in_image_file_name, 'rb') as f:
binary = f.read()
data = {
"name": out_image_file_name,
"type": 'image/png',
"overwrite": True,
"bits": binary
}
media_id = wp.call(media.UploadFile(data))['id']
print(in_image_file_name.split('/')
[-1], 'Upload Success : id=%s' % media_id)
return media_id
else:
print(in_image_file_name.split('/')[-1], 'NO IMAGE!!')
# Set URL, ID, Password
WORDPRESS_ID = "YourID"
WORDPRESS_PW = "YourPassword"
WORDPRESS_URL = "YourURL/xmlrpc.php"
wp = Client(WORDPRESS_URL, WORDPRESS_ID, WORDPRESS_PW)
# Picture file name & Upload
imgPath = "picture.png "
media_id = upload_image(imgPath, imgPath)
# Blog Title
title = "Article title"
# Blog Content (html)
body = """
<p>Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body Body</p>
<h2>Heading</h2>
<figure class="wp-block-image alignwide size-large">
<img src="YourURL/wp-content/uploads/year/month/%s" alt="" class="wp-image-%s"/>
</figure>
""" %(imgPath, media_id)
# publish or draft
status = "draft"
#Category keyword
cat1 = 'category1'
cat2 = 'category2'
cat3 = 'category3'
#Tag keyword
tag1 = 'tag1'
tag2 = 'tag2'
tag3 = 'tag3'
slug = "slug"
# Post
post = WordPressPost()
post.title = title
post.content = body
post.post_status = status
post.terms_names = {
"category": [cat1, cat2, cat3],
"post_tag": [tag1, tag2, tag3],
}
post.slug = slug
# Set eye-catch image
post.thumbnail = media_id
# Post Time
post.date = datetime.datetime.now() - datetime.timedelta(hours=9)
wp.call(NewPost(post))
I think there is a better way to write the image link, but if I find an improvement, I'll fix it.
It is very easy because you can process the data with Python, create a graph, make an article with a graph as it is, post it to WordPress and automate it. I want to utilize it from now on.
I referred to various articles. Thank you very much.
-Automatically post to wordpress with Python (python-wordpress-xmlrpc)
-Post from python to WordPress & upload images
-Post to WordPress with Python and get list
-[python] Automatic posting to WordPress
Recommended Posts