Post an article with an image to WordPress with Python

Introduction

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.

How to post from Python to WordPress

It seems that there are two types of methods, but here I used Python-wordpress-xmlrpc.

python-wordpress-xmlrpc

usage environment

$python -V
Python 3.8.3

Installation

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

Sample code for posting an article with an image

# 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))

Task

I think there is a better way to write the image link, but if I find an improvement, I'll fix it.

effect

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.

Reference site

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

Post an article with an image to WordPress with Python
How to crop an image with Python + OpenCV
Post to slack with Python 3
Cut out an image with python
Easily post to twitter with Python 3
HTML email with image to send with python
Introduction to Python Image Inflating Image inflating with ImageDataGenerator
Try to generate an image with aliasing
Sample to convert image to Wavelet with Python
Try to extract a character string from an image with Python3
I tried to make an image similarity function with Python + OpenCV
Convert PDF to image (JPEG / PNG) with Python
Image characters and post to slack (python slackbot)
Send an email to Spushi's address with python
Post youtube soaring title to twitter with python3
POST photos with Microsoft Bing Image Search API to get Image Insights (Python)
Image processing with Python
An article summarizing the pitfalls addicted to python
[AWS] How to deal with WordPress "An error occurred when cropping an image."
I want to convert an image to WebP with lollipop
How to scrape image data from flickr with python
An introduction to Python distributed parallel processing with Ray
Reading Note: An Introduction to Data Analysis with Python
Convert the image in .zip to PDF with Python
I tried to implement an artificial perceptron with python
How to create an image uploader in Bottle (Python)
Image processing with Python (Part 2)
Connect to BigQuery with Python
Post from Python to Slack
Post to vim → Python → Slack
POST json with Python3 script
Image editing with python OpenCV
Connect to Wikipedia with Python
Creating an egg with python
Sorting image files with Python (2)
Sorting image files with Python (3)
Post to Twitter using Python
Image processing with Python (Part 1)
Tweet with image in Python
Sorting image files with Python
Image processing with Python (Part 3)
Post to Slack in Python
[Python] Image processing with scikit-image
I tried to find the entropy of the image with python
How to convert an array to a dictionary with Python [Application]
[Ev3dev] How to display bmp image on LCD with python
Post a message to Google Hangouts Chat with a thread (Python)
[Let's play with Python] Image processing to monochrome and dots
How to run an app built with Python + py2app built with Anaconda
[Python Kivy] How to create an exe file with pyinstaller
How to read an Excel file (.xlsx) with Pandas [Python]
I tried to create an article in Wiki.js with SQLAlchemy
Python: How to use async with
Link to get started with python
[Python] Write to csv file with Python
[Python] Using OpenCV with Python (Image transformation)
Create folders from '01' to '12' with python
Try to operate Facebook with Python
Post from python to facebook timeline
Output to csv file with Python
[Python] POST wav files with requests [POST]