diff --git a/src/index.js b/src/index.js index 05bfda0..77cb858 100644 --- a/src/index.js +++ b/src/index.js @@ -11,6 +11,7 @@ import { getAllTerms, deleteAllTerms, getTermBySlug, + createTerm, } from './taxonomies/index.js'; import { fillInXliffExportForm, getXliffRegex } from './xliff/index.js'; import { getDownload, getStringFromFile } from './downloads/index.js'; @@ -30,6 +31,7 @@ export { getAllTerms, deleteAllTerms, getTermBySlug, + createTerm, fillInXliffExportForm, getDownload, getXliffRegex, diff --git a/src/taxonomies/index.js b/src/taxonomies/index.js index 06bcfa8..ddf3bfb 100644 --- a/src/taxonomies/index.js +++ b/src/taxonomies/index.js @@ -37,6 +37,41 @@ export const getTermBySlug = async ( requestUtils, taxonomy, slug ) => { } ); }; +let termCounter = 0; + +/** + * Creates a term. + * + * @param {RequestUtils} requestUtils Gutenberg request utils object. + * @param {string} taxonomy Taxonomy slug used in related REST endpoint (e.g., 'categories', 'tags'). + * @param {Object} [args = {}] Additional arguments to pass to the request. + * @param {string} [args.name] Term name (required). + * @param {string} [args.description] Term description. + * @param {string} [args.slug] Term slug. + * @param {number} [args.parent] Parent term ID. + * @param {string} [args.lang] Language slug. + * @return {Promise} Request promise. + */ +export const createTerm = async ( + requestUtils, + taxonomy = 'categories', + args = {} +) => { + const defaultArgs = { + ...args, + }; + + if ( ! defaultArgs.name ) { + defaultArgs.name = `Term ${ ++termCounter }`; + } + + return requestUtils.rest( { + method: 'POST', + path: `${ BASE_PATH }/${ taxonomy }`, + data: defaultArgs, + } ); +}; + /** * Deletes all terms. *