Skip to content

Instantly share code, notes, and snippets.

@panayotoff
Created November 1, 2019 22:25
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 panayotoff/663a478c881702e8ea2a95956df70d59 to your computer and use it in GitHub Desktop.
Save panayotoff/663a478c881702e8ea2a95956df70d59 to your computer and use it in GitHub Desktop.
NodeJS + wp-cli post seeder
const util = require('util');
const exec = util.promisify(require('child_process').exec);
const wp_path = '/Users/<User>/Documents/Sites/<WP>';
async function seed(postData = {}, rawArgs = {}) {
const wpArgs = { ...rawArgs };
let postId;
let featuredImageId;
const meta = { ...postData.meta };
if (!postData.title) throw new Error('Post needs title');
if (!postData.content) throw new Error('Post needs content');
wpArgs['--post_title'] = postData.title;
wpArgs['--post_content'] = postData.content;
if (postData.category) {
// Pass as WP array
if (typeof postData.category === 'object') {
postData.category = postData.category.join(',');
}
}
if (postData.postType) {
wpArgs['--post_type'] = postData.postType;
}
wpArgs['--meta_input'] = JSON.stringify(meta);
// Create post
let execArgs = Object.keys(wpArgs).reduce((cmd, key) => {
if (wpArgs[key]) {
return `${cmd} ${key}="${wpArgs[key]}"`;
}
return `${cmd} ${key}`;
}, 'wp post create --porcelain --post_status="publish"');
const { stdout, stderr, error } = await exec(execArgs, { shell: true, cwd: wp_path });
if (error || stderr) throw new Error(error || stderr);
postId = parseInt(stdout);
// Add featured image
if (postData.featuredImage) {
let { error, stdout, stderr } = await exec(`wp media import ${postData.featuredImage} --post_id="${postId}" --featured_image --porcelain`, { shell: true, cwd: wp_path });
if (error || stderr) throw new Error(error || stderr);
featuredImageId = parseInt(stdout);
}
console.log(`${wpArgs['post']}`);
}
/**
* Example
*/
seed({
title: 'post title',
content: 'post <strong>text</strong>',
postType: 'page',
featuredImage: 'imgurl.jpg',
meta: {
subtitle: 'ACF field named subtitle'
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment