Hire 
Voiceflow Community
Submit
Note: Voiceflow is not responsible for the exchange of services between you and the partner.
Thank you! An email will be sent connecting you with the expert.
Oops! Something went wrong while submitting the form.

WordPress: Create New Post

Template
Function
5
Template
Function
by
Voiceflow Community

Creates a new WordPress post with a given title and content

Created:

Heading

Voiceflow APIs used:

Channels
No items found.
Created By
Voiceflow Community
This is some text inside of a div block.

Function Code Snippet

 
export default async function main(args) {
const { wpUsername, wpDomain, wpApikey, wpPostTitle, wpPostContent } = args.inputVars

// Custom function to manually encode a string to Base64
function base64Encode(str) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let output = '';
let chr1, chr2, chr3, enc1, enc2, enc3, enc4;
let i = 0;

while (i < str.length) {
chr1 = str.charCodeAt(i++);
chr2 = i < str.length ? str.charCodeAt(i++) : NaN; // Not defined if the index is out of range
chr3 = i < str.length ? str.charCodeAt(i++) : NaN; // Not defined if the index is out of range

enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;

if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}

output += chars.charAt(enc1) + chars.charAt(enc2) + chars.charAt(enc3) + chars.charAt(enc4);
}

return output;
}

const base64Credentials = base64Encode(`${wpUsername}:${wpApikey}`);

const headers = {
"Authorization": `Basic ${base64Credentials}`,
"Content-Type": "application/json"
};

const postData = {
title: `${wpPostTitle}`,
content: `${wpPostContent}`
};

const body = JSON.stringify(postData);

try {
const response = await fetch(`https://${wpDomain}/wp-json/wp/v2/posts`, {
method: 'POST',
headers: headers,
body: body
});

if (!response.ok) {
const errorResponse = await response.text();
console.log('HTTP Error Status:', response.status);
console.log('Error Response:', errorResponse);
throw new Error('Failed to create post');
}

const result = await response.json;
console.log('Post Created:', result);
return {
next: { path: 'success' },
outputVars: { postId: result.id }
};
} catch (error) {
console.log('Error:', error);
return {
next: { path: 'error' },
trace: [{ type: "debug", payload: { message: "Error:" + error.message } }]
};
}
}
copy-icon

Explore More Templates

Build and submit a Template to have it featured in the community.

ghraphic
No items found.
No items found.