Home Web Front-end JS Tutorial AWS JavaScript WordPress = Fun Content Automation Strategies Using Artificial Intelligence

AWS JavaScript WordPress = Fun Content Automation Strategies Using Artificial Intelligence

Jan 05, 2025 pm 08:40 PM

Months ago, I began collaborating on a project all about AI generated content for a client focused on the tech sector. My role was mostly focused on setting up SSG using WordPress as a Headless CMS for a Nuxt Front-end.

The client used to write articles a couple of times per week about different trends or situations affecting the sector, in the hope of increasing traffic to the site and its output of articles he decided to use AI to generate articles for him.

After some time, with the right prompts the client had pieces of information that were close to an exact match of a human written article, it is super difficult to spot they are machine made.

Sometime after I moved to work on different features, I would continuously get asked one specific thing.

Ey, can you update the featured image for this article?

After 2 weeks of daily updating Posts I had a small eureka moment.

AWS   JavaScript   WordPress = Fun Content Automation Strategies Using Artificial Intelligence

Why don't I automate the featured image generation for these articles using Artifical Intelligence?

We already automated post writing, why don't automate the featured images?

In my free time, I was experimenting with generative LLMs on my computer so I had a solid idea of more or less how to tackle this side-quest. I sent a message to the client detailing what is the problem, what I want to do and what were going to be the advantages and without having to do convincing, I got the green-lit to work on this feature and right away I went with my first step.

1. Architecting how the solution is going to look.

Given that I had some exposure to running models locally I knew right away it was not feasible to self host those models. With that discarded I started to play around APIs that generated images based on text prompts.

Featured images consisted of 2 parts: the main composed graphic and a catchy tagline.

The composed graphic would be some elements related to the article, arranged in a nice way with then some colors and textures with some blend modes applied to achieve some fancy effects following the branding.

Taglines were short, 8-12 words sentences with a simple drop shadow under them.

Based on my testing, I realized that pursuing the AI route for image generation wasn’t practical. The image quality didn’t meet expectations, and the process was too time-consuming to justify its use. Considering this would run as an AWS Lambda function, where execution time directly impacts costs.

With that discarded, I went with Plan B: mashing images and design assets together using JavaScript's Canvas API.

Taking a deep look we had mainly 5 styles of simple posts, and around 4 types of textures and 3 of them using the same text alignment, style and position. After doing some math I thought:

Hmm, If i take these 3 images, grab 8 textures and play with blend-modes, I can get around post 24 variations

Given that those 3 types of posts had the same text style it was practically one template.

With that settled, I moved to the Tagline Generator. I wanted to create a tagline based on the content and title of the article. I decided to use ChatGPT’s API given that the company was already paying for it, and after some experimenting and promps tweaking, I had a very good MVP for my tagline generator.

With the 2 hardest parts of the task figured out, I spent some time in Figma putting together the diagram for the final architecture of my service.

AWS   JavaScript   WordPress = Fun Content Automation Strategies Using Artificial Intelligence

2.Coding my lambda

The plan was to create a Lambda function capable of analyzing post content, generating a tagline, and assembling a featured image—all seamlessly integrated with WordPress.

I will provide some code but just enough to communicate the overall idea to ke.

Analyzing the content

The Lambda function starts by extracting the necessary parameters from the incoming event payload:

const { title: request_title, content, backend, app_password} = JSON.parse(event.body);

  • title and content: These provide the article’s context.
  • backend: The WordPress backend URL for image uploads.
  • app_password: The authentication token im going to use to upload as my user using Wordpress Rest API.

Generating the Tagline

The function’s first major task is to generate a tagline using analyzeContent function, which uses OpenAI’s API to craft a click-worthy tagline based on the article's title and content.

Our function takes the post title and content but returns a tagline, post sentiment to know if post is a positive, negative or neutral opinion and an optional company symbol from the S&P index companies.

const { tagline, sentiment, company } = await analyzeContent({ title: request_title, content });

This step is critical, as the tagline directly influences the image’s aesthetics.

Creating the Featured Image

Next, the generateImage function kicks in:

let buffer;

buffer = await generateImage({
    title: tagline,
    company_logo: company_logo,
    sentiment: sentiment,
});

Copy after login
Copy after login

This function handles:

  • Designing the composition.
  • Layering textures, colors, and branding elements.
  • Applying effects and creating the title.

Here is a step by step breakdown on how it works:

The generateImage function begins by setting up a blank canvas, defining its dimensions, and preparing it to handle all the design elements.

let buffer;

buffer = await generateImage({
    title: tagline,
    company_logo: company_logo,
    sentiment: sentiment,
});

Copy after login
Copy after login

From there, a random background image is loaded from a predefined collection of assets. These images were curated to suit the tech-oriented branding while allowing for enough variety across posts. Background image is selected randomly based on its sentiment.

To ensure each background image looked great, I calculated its dimensions dynamically based on the aspect ratio. This avoids distortions while keeping the visual balance intact.

Adding the Tagline

The tagline is short but based on some rules, this impactful sentence is split into manageable pieces and is styled dynamically to ensure it’s always readable, regardless of length or canvas size based on the word count for the line, word length, etc.

const COLOURS = {
        BLUE: "#33b8e1",
        BLACK: "#000000",
    }

    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    const images_path = path.join(__dirname, 'images/');
    const files_length = fs.readdirSync(images_path).length;
    const images_folder = process.env.ENVIRONMENT === "local"
        ? "./images/" : "/var/task/images/";


    registerFont("/var/task/fonts/open-sans.bold.ttf", { family: "OpenSansBold" });
    registerFont("/var/task/fonts/open-sans.regular.ttf", { family: "OpenSans" });


    console.log("1. Created canvas");

    const canvas = createCanvas(1118, 806);

    let image = await loadImage(`${images_folder}/${Math.floor(Math.random() * (files_length - 1 + 1)) + 1}.jpg`);


    let textBlockHeight = 0;

    console.log("2. Image loaded");

    const canvasWidth = canvas.width;
    const canvasHeight = canvas.height;
    const aspectRatio = image.width / image.height;


    console.log("3. Defined ASPECT RATIO",)

    let drawWidth, drawHeight;
    if (image.width > image.height) {
        // Landscape orientation: fit by width
        drawWidth = canvasWidth;
        drawHeight = canvasWidth / aspectRatio;
    } else {
        // Portrait orientation: fit by height
        drawHeight = canvasHeight;
        drawWidth = canvasHeight * aspectRatio;
    }

    // Center the image
    const x = (canvasWidth - drawWidth) / 2;
    const y = (canvasHeight - drawHeight) / 2;
    const ctx = canvas.getContext("2d");
    console.log("4. Centered Image")
    ctx.drawImage(image, x, y, drawWidth, drawHeight);

Copy after login

Finally, the canvas is converted into a PNG buffer.

console.log("4.1 Text splitting");
if (splitText.length === 1) {

    const isItWiderThanHalf = ctx.measureText(splitText[0]).width > ((canvasWidth / 2) + 160);
    const wordCount = splitText[0].split(" ").length;

    if (isItWiderThanHalf && wordCount > 4) {

        const refactored_line = splitText[0].split(" ").reduce((acc, curr, i) => {
            if (i % 3 === 0) {
                acc.push([curr]);
            } else {
                acc[acc.length - 1].push(curr);
            }
            return acc;
        }, []).map((item) => item.join(" "));

        refactored_line[1] = "[s]" + refactored_line[1] + "[s]";

        splitText = refactored_line

    }
}

let tagline = splitText.filter(item => item !== '' && item !== '[br]' && item !== '[s]' && item !== '[/s]' && item !== '[s]');
let headlineSentences = [];
let lineCounter = {
    total: 0,
    reduced_line_counter: 0,
    reduced_lines_indexes: []
}

console.log("4.2 Tagline Preparation", tagline);

for (let i = 0; i < tagline.length; i++) {
    let line = tagline[i];

    if (line.includes("[s]") || line.includes("[/s]")) {

        const finalLine = line.split(/(\[s\]|\[\/s\])/).filter(item => item !== '' && item !== '[s]' && item !== '[/s]');

        const lineWidth = ctx.measureText(finalLine[0]).width
        const halfOfWidth = canvasWidth / 2;

        if (lineWidth > halfOfWidth && finalLine[0]) {

            let splitted_text = finalLine[0].split(" ").reduce((acc, curr, i) => {

                const modulus = finalLine[0].split(" ").length >= 5 ? 3 : 2;
                if (i % modulus === 0) {
                    acc.push([curr]);
                } else {
                    acc[acc.length - 1].push(curr);
                }
                return acc;
            }, []);

            let splitted_text_arr = []

            splitted_text.forEach((item, _) => {
                let lineText = item.join(" ");

                item = lineText

                splitted_text_arr.push(item)
            })

            headlineSentences[i] = splitted_text_arr[0] + '/s/'

            if (splitted_text_arr[1]) {
                headlineSentences.splice(i + 1, 0, splitted_text_arr[1] + '/s/')
            }
        } else {
            headlineSentences.push("/s/" + finalLine[0] + "/s/")
        }


    } else {
        headlineSentences.push(line)
    }
}

console.log("5. Drawing text on canvas", headlineSentences);

const headlineSentencesLength = headlineSentences.length;
let textHeightAccumulator = 0;

for (let i = 0; i < headlineSentencesLength; i++) {
    headlineSentences = headlineSentences.filter(item => item !== '/s/');
    const nextLine = headlineSentences[i + 1];
    if (nextLine && /^\s*$/.test(nextLine)) {
        headlineSentences.splice(i + 1, 1);
    }

    let line = headlineSentences[i];

    if (!line) continue;
    let lineText = line.trim();

    let textY;

    ctx.font = " 72px OpenSans";

    const cleanedUpLine = lineText.includes('/s/') ? lineText.replace(/\s+/g, ' ') : lineText;
    const lineWidth = ctx.measureText(cleanedUpLine).width
    const halfOfWidth = canvasWidth / 2;

    lineCounter.total += 1

    const isLineTooLong = lineWidth > (halfOfWidth + 50);

    if (isLineTooLong) {

        if (lineText.includes(':')) {
            const split_line_arr = lineText.split(":")
            if (split_line_arr.length > 1) {
                lineText = split_line_arr[0] + ":";
                if (split_line_arr[1]) {
                    headlineSentences.splice(i + 1, 0, split_line_arr[1])
                }
            }
        }

        ctx.font = "52px OpenSans";

        lineCounter.reduced_line_counter += 1

        if (i === 0 && headlineSentencesLength === 2) {
            is2LinesAndPreviewsWasReduced = true
        }


        lineCounter.reduced_lines_indexes.push(i)

    } else {

        if (i === 0 && headlineSentencesLength === 2) {
            is2LinesAndPreviewsWasReduced = false
        }


    }

    if (lineText.includes("/s/")) {

        lineText = lineText.replace(/\/s\//g, "");

        if (headlineSentencesLength > (i + 1) && i < headlineSentencesLength - 1 && nextLine) {

            if (nextLine.slice(0, 2).includes("?") && nextLine.length < 3) {
                lineText += '?';
                headlineSentences.pop();
            }

            if (nextLine.slice(0, 2).includes(":")) {
                lineText += ':';
                headlineSentences[i + 1] = headlineSentences[i + 1].slice(2);
            }

        }

        let lineWidth = ctx.measureText(lineText).width


        let assignedSize;


        if (lineText.split(" ").length <= 2) {

            if (lineWidth > (canvasWidth / 2.35)) {

                ctx.font = "84px OpenSansBold";

                assignedSize = 80

            } else {

                ctx.font = "84px OpenSansBold";

                assignedSize = 84

            }
        } else {


            if (i === headlineSentencesLength - 1 && lineWidth < (canvasWidth / 2.5) && lineText.split(" ").length === 3) {

                ctx.font = "84px OpenSansBold";
                assignedSize = 84

            } else {

                lineCounter.reduced_line_counter += 1;

                ctx.font = "52px OpenSansBold";
                assignedSize = 52

            }

            lineCounter.reduced_lines_indexes.push(i)

        }

        lineWidth = ctx.measureText(lineText).width



        if (lineWidth > (canvasWidth / 2) + 120) {

            if (assignedSize === 84) {
                ctx.font = "72px OpenSansBold";
            } else if (assignedSize === 80) {
                ctx.font = "64px OpenSansBold";

                textHeightAccumulator += 8
            } else {
                ctx.font = "52px OpenSansBold";
            }
        }



    } else {

        const textWidth = ctx.measureText(lineText).width


        if (textWidth > (canvasWidth / 2)) {
            ctx.font = "44px OpenSans";
            textHeightAccumulator += 12
        } else if (i === headlineSentencesLength - 1) {
            textHeightAccumulator += 12
        }

    }

    ctx.fillStyle = "white";
    ctx.textAlign = "center";

    const textHeight = ctx.measureText(lineText).emHeightAscent;

    textHeightAccumulator += textHeight;

    if (headlineSentencesLength == 3) {
        textY = (canvasHeight / 3)
    } else if (headlineSentencesLength == 4) {
        textY = (canvasHeight / 3.5)
    } else {
        textY = 300
    }

    textY += textHeightAccumulator;

    const words = lineText.split(' ');
    console.log("words", words, lineText, headlineSentences)
    const capitalizedWords = words.map(word => {
        if (word.length > 0) return word[0].toUpperCase() + word.slice(1)
        return word
    });
    const capitalizedLineText = capitalizedWords.join(' ');

    ctx.fillText(capitalizedLineText, canvasWidth / 2, textY);

}

Copy after login

Finally!!! Uploading the Image to WordPress

After successfully generating the image buffer, the uploadImageToWordpress function is called.

This function handles the heavy lifting of sending the image to WordPress using its REST API by Encoding the Image for WordPress.

The function first prepares the tagline for use as the filename by cleaning up spaces and special characters:

const buffer = canvas.toBuffer("image/png");
return buffer;
Copy after login

The image buffer is then converted into a Blob object to make it compatible with the WordPress API:

const file = new Blob([buffer], { type: "image/png" });

Preparing the API Request Using the encoded image and tagline, the function builds a FormData object and I add optional metadata, such as alt_text for accessibility and a caption for context.

const createSlug = (string) => {
    return string.toLowerCase().replace(/ /g, '-').replace(/[^\w-]+/g, '');
};

const image_name = createSlug(tagline);
Copy after login

For authentication, the username and application password are encoded in Base64 and included in the request headers:

formData.append("file", file, image_name + ".png");
formData.append("alt_text", `${tagline} image`);
formData.append("caption", "Uploaded via API");
Copy after login

Sending the Image A POST request is made to the WordPress media endpoint with the prepared data and headers and after awaiting the response I validate for success or errors.

const credentials = `${username}:${app_password}`;
const base64Encoded = Buffer.from(credentials).toString("base64");

Copy after login

If successful, I return that same media response in the lambda.

This is how my lambda looks in the end.

const response = await fetch(`${wordpress_url}wp-json/wp/v2/media`, {
    method: "POST",
    headers: {
        Authorization: "Basic " + base64Encoded,
        contentType: "multipart/form-data",
    },
    body: formData,
});

if (!response.ok) {
    const errorText = await response.text();
    throw new Error(`Error uploading image: ${response.statusText}, Details: ${errorText}`);
}

Copy after login

This is a sample image produced by my script. It's not used in production, just created with generic assets for this example.

AWS   JavaScript   WordPress = Fun Content Automation Strategies Using Artificial Intelligence

Aftermath

Some time has passed and everybody is happy that we no longer have shoddy or empty looking image-less articles, that images are a close match to the ones that the designer crafts, the designer is happy that he gets to only focus on designing for other marketing efforts across the company.

But then a new problem arose: sometimes the client did not like the Image generated and he would ask me to spin up my script to generate a new one for a specific post.

This brought me to my next sidequest: A Wordpress Plugin to Manually Generate a Featured image using Artificial Inteligence for an Specific Post

The above is the detailed content of AWS JavaScript WordPress = Fun Content Automation Strategies Using Artificial Intelligence. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1669
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript and the Web: Core Functionality and Use Cases JavaScript and the Web: Core Functionality and Use Cases Apr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript in Action: Real-World Examples and Projects JavaScript in Action: Real-World Examples and Projects Apr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding the JavaScript Engine: Implementation Details Understanding the JavaScript Engine: Implementation Details Apr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: Community, Libraries, and Resources Python vs. JavaScript: Community, Libraries, and Resources Apr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Python vs. JavaScript: Development Environments and Tools Python vs. JavaScript: Development Environments and Tools Apr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles