WordPress.com: Create Draft Post

WordPress.com: Create Draft Post

WordPress.com: 下書き記事作成

This item creates a post in draft status on WordPress.com.

Basic Configs
Step Name
Note
Auto Step icon
Configs for this Auto Step
conf_Auth
C1: OAuth2 Setting *
conf_Domain
C2: Domain of the WordPress.com site *
conf_Title
C3: Title#{EL}
conf_Content
C4: Content *#{EL}
conf_Excerpt
C5: Excerpt#{EL}
conf_Slug
C6: Slug#{EL}
conf_FeaturedImage
C7: Media ID for Featured Image
conf_Categories
C8: Category IDs (write one per line)
conf_Tags
C9: Tag IDs (write one per line)
conf_PostId
C10: Data item to save Post ID
conf_PostUrl
C11: Data item to save URL of the post

Notes

  • This Auto Step is for WordPress.com (a service that hosts WordPress sites, provided by Automattic itself)
  • OAuth2 settings should be created per user per site
    • When the same user handles multiple WordPress.com sites, create an OAuth2 setting for each site
  • IDs of Media, Categories and Tags are not displayed on WordPress.com Web UI, so please use the following items to retrieve IDs:
  • To get Media ID of an already uploaded media :
    1. Open Media Library on WordPress.com Web UI
    2. Switch to Classic View
    3. Click a media, and its Media ID will be shown in the URL in either of the following format
      • ?item={Media ID}
      • ?post={Media ID}
  • When the specified Media ID, Category ID or Tag ID does not exist, it will be ignored

Capture

See Also

Script (click to open)
  • An XML file that contains the code below is available to download
    • wordpress-post-create.xml (C) Questetra, Inc. (MIT License)
    • If you are using Professional, you can modify the contents of this file and use it as your own add-on auto step

// OAuth2 config sample at [OAuth 2.0 Setting]
// - Authorization Endpoint URL: https://public-api.wordpress.com/oauth2/authorize
// - Token Endpoint URL: https://public-api.wordpress.com/oauth2/token
// - Scope: posts
// - Client ID: (Get by https://developer.wordpress.com/apps/)
// - Client Secret: (Get by https://developer.wordpress.com/apps/)

const API_VERSION = 'v1.1';

const main = () => {
    ////// == 工程コンフィグ・ワークフローデータの参照 / Config & Data Retrieving ==
    const auth = configs.getObject('conf_Auth');
    const domain = configs.get('conf_Domain');
    const title = configs.get('conf_Title');
    const content = configs.get('conf_Content');
    if (content === '') {
        throw new Error('Content is blank.');
    }
    const excerpt = configs.get('conf_Excerpt');
    const slug = configs.get('conf_Slug');
    const featuredImage = retrieveId('conf_FeaturedImage', 'Media ID for Featured Image');
    const categoryIds = retrieveIdsAsList('conf_Categories', 'Category ID');
    const tagIds = retrieveIdsAsList('conf_Tags', 'Tag ID');

    ////// == 演算 / Calculating ==
    const {postId, postUrl} = createPost(auth, domain, title, content, excerpt, slug, featuredImage, categoryIds, tagIds);

    ////// == ワークフローデータへの代入 / Data Updating ==
    saveData('conf_PostId', postId);
    saveData('conf_PostUrl', postUrl);
};

/**
  * config に設定された ID を読み出す
  * @param {String} confName 設定名
  * @param {String} label エラーメッセージ用ラベル
  * @return {String} id
  */
const retrieveId = (confName, label) => {
    const dataDef = configs.getObject(confName);
    if (dataDef === null) {
        return null;
    }
    // 文字型データ項目の場合
    if (dataDef.matchDataType('STRING_TEXTFIELD')) {
        const id =  engine.findData(dataDef);
        if (id === null) {
            return null;
        }
        validateId(id, label);
        return id;
    }
    // 選択型データ項目の場合
    const selects = engine.findData(dataDef);
    if (selects === null || selects.size() === 0) {
        return null;
    }
    const id = selects.get(0).getValue(); // 選択肢 ID
    validateId(id, label);
    return id;
};

/**
 * ID の値をチェックする
 * 非負整数でない場合はエラー
 * @param {String} id
 * @param {String} label エラーメッセージ用ラベル
 */
const validateId = (id, label) => {
    const idReg = new RegExp('^(0|[1-9][0-9]*)$');
    if (!idReg.test(id)) {
        throw new Error(`${label} must be a non-negative integer.`);
    }
};

/**
  * config に設定された ID の一覧を読み出す
  * @param {String} confName 設定名
  * @param {String} label エラーメッセージ用ラベル
  * @return {Array<String>} ids
  */
const retrieveIdsAsList = (confName, label) => {
    const dataDef = configs.getObject(confName);
    if (dataDef === null) {
        return [];
    }
    // 文字型データ項目の場合
    if (dataDef.matchDataType('STRING')) {
        const dataObj = engine.findData(dataDef);
        if (dataObj === null) {
            return [];
        }
        const ids = dataObj.split('\n')
            .filter(id => id !== '');
        validateIds(ids, label);
        return ids;
    }
    // 選択型データ項目の場合
    const selects = engine.findData(dataDef);
    if (selects === null || selects.size() === 0) {
        return [];
    }
    const ids = [];
    selects.forEach(item => {
        ids.push(item.getValue()); // 選択肢 ID を格納
    });
    validateIds(ids, label);
    return ids;
};

/**
 * ID の一覧をチェックする
 * 非負整数でない場合はエラー
 * @param {Array<String>} ids
 * @param {String} label エラーメッセージ用ラベル
 */
const validateIds = (ids, label) => {
    ids.forEach(id => validateId(id, label));
};

/**
 * 投稿を作成する
 * @param {AuthSettingWrapper} auth
 * @param {String} domain
 * @param {String} title
 * @param {String} content
 * @param {String} excerpt
 * @param {String} slug
 * @param {String} featuredImage
 * @param {Array<String>} categories
 * @param {Array<String>} tags
 * @return {String} postId
 */
const createPost = (auth, domain, title, content, excerpt, slug, featuredImage, categories, tags) => {
    const url = `https://public-api.wordpress.com/rest/${API_VERSION}/sites/${encodeURIComponent(domain)}/posts/new`;
    const payload = { title, content, excerpt, slug, featured_image: featuredImage, categories, tags, status: 'draft' };
    const response = httpClient.begin().authSetting(auth)
        .queryParam('fields', 'ID,URL')
        .body(JSON.stringify(payload), 'application/json')
        .post(url);
    const status = response.getStatusCode();
    const responseStr = response.getResponseAsString();
    if (status !== 200) {
        engine.log(responseStr);
        throw new Error(`Failed to create post. status: ${status}`);
    }
    const postObj = JSON.parse(responseStr);
    return {
        postId: String(postObj.ID),
        postUrl: postObj.URL
    };
};

/**
 * データ項目への保存
 * @param configName
 * @param data
 */
const saveData = (configName, data) => {
    const def = configs.getObject(configName);
    if (def === null) {
        return;
    }
    engine.setData(def, data);
};

    

Discover more from Questetra Support

Subscribe now to keep reading and get access to the full archive.

Continue reading