Back to all functions

WordPress: Get Post by ID

Retrieve a specific post using the WordPress post ID

Created By
Voiceflow Community
Community
download-icon
INPUT VARIABLES
{
wpPostId
}
The ID of the post you want to update
{
wpApikey
}
Get your key from WP backend > User > Profile > Add New Application Password
{
wpUsername
}
Your usual WP login username
{
wpDomain
}
your-domain.com
{
wpPostTitle
}
The title for your post
{
}
share-icon
OUTPUT VARIABLES
{
wpContent
}
The body text of your post
{
wpTitle
}
The title of your post
{
}
{
}
{
}
{
}
paths-icon
PATHS
{
success
}
Success
{
Error
}
{
}
{
}
{
}
{
}

Function Walkthrough

Function Code Snippet

 
export default async function main(args) {

    const { wpUsername, wpDomain, wpApikey, wpPostId } = args.inputVars;

    // Custom function to encode a string to Base64
    function base64Encode(str) {
        const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
        let encoded = '', i = 0;

        while (i < str.length) {
            const a = str.charCodeAt(i++);
            const b = i < str.length ? str.charCodeAt(i++) : 0;
            const c = i < str.length ? str.charCodeAt(i++) : 0;

            const b1 = (a >> 2) & 0x3F;
            const b2 = ((a & 0x03) << 4) | ((b >> 4) & 0x0F);
            const b3 = ((b & 0x0F) << 2) | ((c >> 6) & 0x03);
            const b4 = c & 0x3F;

            if (!i) {
                encoded += chars.charAt(b1) + chars.charAt(b2) + '==';
            } else if (i == str.length + 1) {
                encoded += chars.charAt(b1) + chars.charAt(b2) + chars.charAt(b3) + '=';
            } else {
                encoded += chars.charAt(b1) + chars.charAt(b2) + chars.charAt(b3) + chars.charAt(b4);
            }
        }

        return encoded;
    }

    const base64Credentials = base64Encode(`${wpUsername}:${wpApikey}`);
    const apiUrl = `https://${wpDomain}/wp-json/wp/v2/posts/${wpPostId}`;  // Append postId to the URL

    // Fetch API data with Basic Authentication
    try {
        const response = await fetch(apiUrl, {
            headers: {
                "Authorization": `Basic ${base64Credentials}`
            }
        });

        // Check if the response was ok (status 200)
        if (response.ok) {
            const post = await response.json;  // Parse JSON response

            return {
                outputVars: {
                    wpTitle: post.title.rendered,
                    wpContent: post.content.rendered
                },
                next: {
                    path: 'success'
                },
                trace: [
                    {
                        type: 'debug',
                        payload: {
                            message: `Fetched post: ${post.title.rendered}`
                        }
                    }
                ],
            };
        } else {
            const errorResponse = await response.text();
            console.log('HTTP Error Status:', response.status);
            console.log('Error Response:', errorResponse);
            throw new Error(`Failed to fetch post: HTTP error! status: ${response.status}`);
        }
    } catch (error) {
        return {
            outputVars: {
                error: error.toString()
            },
            next: {
                path: 'error'
            },
            trace: [
                {
                    type: 'debug',
                    payload: {
                        message: `Error fetching post: ${error}`
                    }
                }
            ],
        };
    }

}
copy-icon

Have something to share?

Share your creation with over 250,000 other global Voiceflow users.

ghraphic
No items found.