Generate an optimized post's featured image using OpenAI's DALL-E and TinyPNG

🔥 This query is already included in Gato GraphQL, as Persisted Query “Generate a post\'s featured image using AI and optimize it”.

This Persisted GraphQL query uses OpenAI's DALL-E generative AI to produce images for posts without a featured image.

It first checks if a post has a featured image. If it does not, it creates one by calling DALL-E's generative AI service. We must provide the API key to use it.

As the generative AI images are not optimized for the web, the query can also send the newly-generated image to TinyPNG to compress it. We must provide the API key to use it.

Finally, the query creates a new media item with the image, and sets it as the post's featured image.

query InitializeVariables(
$tinyPngAPIKey: String
)
@configureWarningsOnExportingDuplicateVariable(enabled: false)
{
isFeaturedImageMissing: _echo(value: false)
@export(as: "isFeaturedImageMissing")
@remove

isPostTitleNotEmpty: _echo(value: false)
@export(as: "isPostTitleNotEmpty")
@remove

generatedImageURL: _echo(value: null)
@export(as: "generatedImageURL")
@remove

isImageGenerated: _echo(value: false)
@export(as: "isImageGenerated")
@remove

mimeType: _echo(value: null)
@export(as: "mimeType")
@remove

isMediaItemCreated: _echo(value: false)
@export(as: "isMediaItemCreated")
@remove

useTinyPng: _notEmpty(value: $tinyPngAPIKey)
@export(as: "useTinyPng")
@remove
}

query ExportPostData(
$postID: ID!
)
@depends(on: "InitializeVariables")
{
post(by: { id: $postID }, status: any) {
hasFeaturedImage
isFeaturedImageMissing: hasFeaturedImage
@boolOpposite
@export(as: "isFeaturedImageMissing")
title
@export(as: "postTitle")
rawTitle
@remove
isPostTitleNotEmpty: _notEmpty(value: $__rawTitle)
@export(as: "isPostTitleNotEmpty")
mediaItemFilename: rawTitle
@default(value: "untitled", condition: IS_EMPTY)
@strLowerCase
@strSubstr(offset: 0, length: 20)
@export(as: "filename")
@remove
}
}

query GenerateImageUsingOpenAI(
$openAIAPIKey: String!
$imageSize: String! = "1024x1024" # 256x256, 512x512, or 1024x1024 pixels
)
@depends(on: "ExportPostData")
@include(if: $isFeaturedImageMissing)
@include(if: $isPostTitleNotEmpty)
{
openAIResponse: _sendJSONObjectItemHTTPRequest(input: {
url: "https://api.openai.com/v1/images/generations",
method: POST,
options: {
auth: {
password: $openAIAPIKey
},
json: {
prompt: $postTitle,
size: $imageSize,
n: 1,
response_format: "url",
}
}
})
@underJSONObjectProperty(by: { key: "data" })
@underArrayItem(index: 0)
@underJSONObjectProperty(by: { key: "url" })
@export(as: "generatedImageURL")

openAPIImageCaption: _sprintf(
string: "Image created by DALL-E using prompt: '%s'",
values: [$postTitle]
)
@export(as: "imageCaption")

openAIMediaItemFilename: _sprintf(
string: "%s.png",
values: [$filename]
)
@export(as: "filename")
}

query CheckIsImageGenerated
@depends(on: "GenerateImageUsingOpenAI")
@include(if: $isFeaturedImageMissing)
@include(if: $isPostTitleNotEmpty)
{
isImageGenerated: _notEmpty(value: $generatedImageURL)
@export(as: "isImageGenerated")
}

query MaybeCompressGeneratedImage(
$tinyPngAPIKey: String
)
@depends(on: "CheckIsImageGenerated")
@include(if: $isImageGenerated)
@include(if: $useTinyPng)
{
compressedImageResponse: _sendHTTPRequest(input: {
url: "https://api.tinify.com/shrink",
method: POST,
options: {
auth: {
password: $tinyPngAPIKey
},
headers: [
{
name: "Content-Type",
value: "application/json"
}
],
json: {
source: {
url: $generatedImageURL
}
}
}
}) {
body
@remove
bodyJSONObject: _strDecodeJSONObject(string: $__body)

mimeType: _objectProperty(
object: $__bodyJSONObject
by: { path: "output.type" }
)
@export(as: "mimeType")

generatedImageURL: header(name: "Location")
@export(as: "generatedImageURL")
}
}

mutation CreateMediaItemFromGeneratedImage
@depends(on: "MaybeCompressGeneratedImage")
@include(if: $isImageGenerated)
{
createMediaItem(input: {
from: {
url: {
source: $generatedImageURL
filename: $filename
}
}
title: $postTitle
caption: $imageCaption
altText: $postTitle
mimeType: $mimeType
}) {
mediaItemID
@export(as: "mediaItemID")
isMediaItemCreated: _notNull(value: $__mediaItemID)
@export(as: "isMediaItemCreated")
@remove

status
errors {
__typename
...on ErrorPayload {
message
}
}
mediaItem {
altText
caption
mimeType
slug
src
title
}
}
}

mutation GenerateOptimizedPostFeaturedImageUsingOpenAI(
$postID: ID!
)
@depends(on: "CreateMediaItemFromGeneratedImage")
@include(if: $isMediaItemCreated)
{
setFeaturedImageOnCustomPost(input: {
customPostID: $postID
mediaItemBy: { id: $mediaItemID }
}) {
status
errors {
__typename
...on ErrorPayload {
message
}
}
customPost {
__typename
...on CustomPost {
featuredImage {
id
altText
caption
mimeType
slug
src
title
}
}
}
}
}

Extensions required for this query permalink

  1. Field Default Value permalink

    Set a field to some default value (whenever it is null or empty).

  2. Field Response Removal permalink

    Remove the output of a field from the response.

  3. Field To Input permalink

    Retrieve the value of a field, manipulate it, and input it into another field or directive, all within the same operation.

  4. Field Value Iteration and Manipulation permalink

    Iterate and manipulate the value elements of array and object fields.

  5. HTTP Client permalink

    Addition of fields to execute HTTP requests against a webserver and fetch their response.

  6. Multiple Query Execution permalink

    Combine multiple queries into a single query, sharing state across them and executing them in the requested order.

  7. PHP Functions via Schema permalink

    Manipulate the field output using standard programming language functions available in PHP.

Bundles containing all extensions required for this query permalink

  1. “All in One Toolbox for WordPress” Bundle permalink

    Achieve all superpowers: All of Gato GraphQL extensions, in a single plugin

  2. “Better WordPress Webhooks” Bundle permalink

    Easily create webhooks to process incoming data from any source or service using advanced tools, directly within the wp-admin

  3. “Private GraphQL Server for WordPress” Bundle permalink

    Use GraphQL to power your application (blocks, themes and plugins), internally fetching data without exposing a public endpoint

  4. “Selective Content Import, Export & Sync for WordPress” Bundle permalink

    Import hundreds of records into your WordPress site from another site or service (such as Google Sheets), and selectively export entries to another site

  5. “Tailored WordPress Automator” Bundle permalink

    Create workflows to automate tasks (to transform data, automatically caption images, send notifications, and more)

  6. “Versatile WordPress Request API” Bundle permalink

    Interact with any external API and cloud service, posting and fetching data to/from them