Skip to content

Instantly share code, notes, and snippets.

@matsubo
Created Nov 12, 2020
Embed
What would you like to do?
Post image to wordpress and use it in the article.
require 'faraday'
require 'base64'
require 'json'
# Generated password using application-passwords plugin
authorization = 'Basic ' + Base64.encode64('username:password')
# post image
wp_api_url = 'https://example.com/wp-json/wp/v2'
connection = Faraday.new(wp_api_url) do |builder|
builder.request :multipart
builder.request :url_encoded
builder.adapter Faraday.default_adapter
end
connection.headers['Authorization'] = authorization
params = { file: Faraday::UploadIO.new('tokyo.png', 'image/png') }
response = JSON.parse(connection.post('media', params).body)
# post article
header = {
'Content-Type' => 'application/json',
'Authorization' => authorization
}
tag = format('
<!-- wp:image {"id":%d,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="%s" alt="" class="wp-image-%s"/></figure>
<!-- /wp:image -->
', response['id'], response['media_details']['sizes']['full']['source_url'], response['id'])
post_data = {
title: '日本語',
content: tag,
status: 'draft', # publish
categories: '1',
slug: 'covidtokyo',
featured_media: response['id'],
tags: '1'
}.to_json
response = Faraday.post(wp_api_url + '/posts', post_data, header)
p JSON.parse(response.body)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment