Skip to content

Instantly share code, notes, and snippets.

@matsubo
Created November 12, 2020 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matsubo/59c79de8def21e1285c45662e3dac0c2 to your computer and use it in GitHub Desktop.
Save matsubo/59c79de8def21e1285c45662e3dac0c2 to your computer and use it in GitHub Desktop.
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