Automatyczne ulepszanie opisu nowego produktu WooCommerce za pomocą ChatGPT
To zapytanie pobiera produkt WooCommerce o podanym ID, przepisuje jego treść za pomocą ChatGPT i zapisuje ją ponownie.
(W następnej sekcji zautomatyzujemy wykonanie tego zapytania za każdym razem, gdy produkt zostanie utworzony.)
Custom Post Type product WooCommerce musi być skonfigurowany jako możliwy do odpytywania przez schema GraphQL, zgodnie z opisem w przewodniku Zezwalanie na dostęp do Custom Post Types.
W tym celu przejdź do strony Ustawień, kliknij zakładkę "Schema Elements Configuration > Custom Posts" i wybierz product z listy możliwych do odpytywania CPT (jeśli nie jest jeszcze zaznaczony).
Aby połączyć się z API OpenAI, musisz podać zmienną $openAIAPIKey z kluczem API.
Opcjonalnie możesz podać wiadomość systemową i prompt do przepisania treści wpisu. Jeśli nie zostaną podane, używane są następujące wartości:
- Wiadomość systemowa (
$systemMessage): "You are an English Content rewriter and a grammar checker" - Prompt (
$prompt): "Please rewrite the following English text, by changing the simple A0-level words and sentences with more beautiful and elegant upper-level English words and sentences, while maintaining the original meaning: "
(Ciąg treści jest dołączany na końcu promptu.)
Ponadto możesz nadpisać domyślną wartość zmiennych $model ("gpt-4o-mini", sprawdź listę modeli OpenAI) oraz podać wartości dla $temperature i $maxCompletionTokens (domyślnie oba null).
query GetProductContent(
$productId: ID!
) {
customPost(by: { id: $productId }, customPostTypes: "product", status: any) {
content
@export(as: "content")
}
}
query RewriteProductContentWithChatGPT(
$openAIAPIKey: String!
$systemMessage: String! = "You are an English Content rewriter and a grammar checker"
$prompt: String! = "Please rewrite the following English text, by changing the simple A0-level words and sentences with more beautiful and elegant upper-level English words and sentences, while maintaining the original meaning: "
$model: String! = "gpt-4o-mini"
$temperature: Float
$maxCompletionTokens: Int
)
@depends(on: "GetProductContent")
{
promptWithContent: _strAppend(
after: $prompt
append: $content
)
openAIResponse: _sendJSONObjectItemHTTPRequest(input: {
url: "https://api.openai.com/v1/chat/completions",
method: POST,
options: {
auth: {
password: $openAIAPIKey
},
json: {
model: $model,
temperature: $temperature,
max_completion_tokens: $maxCompletionTokens,
messages: [
{
role: "system",
content: $systemMessage
},
{
role: "user",
content: $__promptWithContent
}
]
}
}
})
@underJSONObjectProperty(by: { key: "choices" })
@underArrayItem(index: 0)
@underJSONObjectProperty(by: { path: "message.content" })
@export(as: "rewrittenContent")
}
mutation UpdateProduct(
$productId: ID!
)
@depends(on: "RewriteProductContentWithChatGPT")
{
updateCustomPost(input: {
id: $productId,
customPostType: "product"
contentAs: {
html: $rewrittenContent
}
}) {
status
errors {
__typename
...on ErrorPayload {
message
}
}
customPost {
__typename
...on CustomPost {
id
content
}
}
}
}Automatyzacja procesu
Możemy użyć Internal GraphQL Server, aby automatycznie wykonać zapytanie za każdym razem, gdy nowy produkt WooCommerce zostanie utworzony.
W tym celu najpierw utwórz nowe utrwalone zapytanie z tytułem "Improve Product Content With ChatGPT" (to przypisze mu slug improve-product-content-with-chatgpt) oraz powyższe zapytanie GraphQL.
Następnie w dowolnym miejscu aplikacji (np. w pliku functions.php, wtyczce lub fragmencie kodu) dodaj poniższy kod PHP, który wykonuje zapytanie na hooku publish_product:
use GatoGraphQL\InternalGraphQLServer\GraphQLServer;
add_action(
'publish_product',
function (int $productId, WP_Post $post, string $oldStatus): void {
// Only execute when it's a newly-published product
if ($oldStatus === 'publish') {
return;
}
GraphQLServer::executePersistedQuery('improve-product-content-with-chatgpt', [
'productId' => $productId,
// Provide your Open AI's API Key
'openAIAPIKey' => '{ OPENAI_API_KEY }',
// Customize any of the other variables, for instance:
'maxCompletionTokens' => 5000,
]);
}, 10, 3
);