Pustaka queries
Pustaka queriesMeningkatkan deskripsi produk WooCommerce baru secara otomatis dengan ChatGPT

Meningkatkan deskripsi produk WooCommerce baru secara otomatis dengan ChatGPT

Query ini mengambil produk WooCommerce dengan ID yang diberikan, menulis ulang kontennya menggunakan ChatGPT, dan menyimpannya kembali.

(Pada bagian berikutnya, kita akan mengotomatiskan eksekusi query ini setiap kali produk dibuat.)

Custom Post Type product milik WooCommerce harus dapat di-query melalui skema GraphQL, sebagaimana dijelaskan dalam panduan Mengizinkan akses ke Custom Post Types.

Untuk melakukannya, buka halaman Settings, klik tab "Schema Elements Configuration > Custom Posts", dan pilih product dari daftar CPT yang dapat di-query (jika belum dipilih).

Untuk terhubung ke API OpenAI, Anda harus menyediakan variabel $openAIAPIKey dengan kunci API-nya.

Anda dapat secara opsional menyediakan pesan sistem dan prompt untuk menulis ulang konten postingan. Jika tidak disediakan, nilai-nilai berikut akan digunakan:

  • Pesan sistem ($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: "

(String konten ditambahkan di akhir prompt.)

Selain itu, Anda dapat menimpa nilai default untuk variabel $model ("gpt-4o-mini", lihat daftar model OpenAI) dan menyediakan nilai untuk $temperature dan $maxCompletionTokens (keduanya null secara default).

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
      }
    }
  }
}

Mengotomatiskan proses

Kita dapat menggunakan Internal GraphQL Server untuk mengeksekusi query secara otomatis setiap kali produk WooCommerce baru dibuat.

Untuk melakukannya, pertama buat persisted query baru dengan judul "Improve Product Content With ChatGPT" (ini akan menetapkan slug improve-product-content-with-chatgpt), beserta query GraphQL di atas.

Kemudian, di mana saja dalam aplikasi Anda (misalnya: di file functions.php, sebuah plugin, atau potongan kode), tambahkan kode PHP berikut, yang mengeksekusi query pada hook 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
);