Skip to content

Instantly share code, notes, and snippets.

@scripting
Last active May 24, 2024 14:16
Show Gist options
  • Save scripting/1fc3f656748dbaa3d84aefc1322aa72c to your computer and use it in GitHub Desktop.
Save scripting/1fc3f656748dbaa3d84aefc1322aa72c to your computer and use it in GitHub Desktop.
Upload a PNG file to a WordPress repo
{
"name": "wpupload",
"description": "Develop and test code to upload images to wordpress.com.",
"version": "0.4.0",
"main": "wpupload.js",
"dependencies" : {
"daveutils": "*",
"wpcom": "*"
}
}
var myProductName = "wpupload", myVersion = "0.4.0";
const fs = require ("fs");
const utils = require ("daveutils");
const wpcom = require ("wpcom");
var config = {
fname: "test.png"
};
function readConfig (f, config, callback) {
fs.readFile (f, function (err, jsontext) {
if (!err) {
try {
jsontext = jsontext.toString ();
var jstruct = JSON.parse (jsontext);
for (var x in jstruct) {
config [x] = jstruct [x];
}
}
catch (err) {
console.log ("Error reading " + f);
}
}
callback ();
});
}
function uploadMedia (accessToken, idSite, fname, theMedia, callback) { //5/24/24 by DW
const wp = wpcom (accessToken);
const site = wp.site (idSite);
const media = site.media ();
const options = {
media: theMedia,
filename: fname,
media_type: "image/png"
}
media.uploadFile (options, function (err, jstruct) {
if (err) {
callback (err);
}
else {
callback (undefined, jstruct);
}
});
}
readConfig ("config.json", config, function (err, data) {
if (err) {
console.log (err.message);
}
else {
console.log ("config == " + utils.jsonStringify (config));
fs.readFile (config.fname, function (err, media) {
if (err) {
console.log (err.message);
}
else {
uploadMedia (config.accessToken, config.idSite, config.fname, media, function (err, data) {
if (err) {
console.log (err.message);
}
else {
console.log (data);
}
});
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment