はい、形態素解析を行ってタイトルから自動でタグを生成することは可能です。ChatGPTのAPIを利用して、WordPressでのタグの自動生成を実現する手順を以下に示します。
- OpenAI APIの準備
- OpenAIのAPIキーを取得します。
- WordPressにプラグインを作成する
- 新しいプラグインのディレクトリとファイルをwp-content/plugins内に作成します。
- プラグインのヘッダー情報を入力します。
- OpenAI APIを呼び出す関数を作成します。
- 形態素解析とタグ生成
- 投稿のタイトルを取得します。
- タイトルをOpenAI APIに送信し、形態素解析を実行します。
- 得られた結果からキーワードやフレーズを取得し、それらをタグとして保存します。
- 投稿の保存時に自動的にタグを生成する
- WordPressの
save_postアクションフックを使用して、投稿が保存されるたびに上記のタグ生成処理を実行します。
- WordPressの
なるほどな。
ソースコードは、参考にはするけど使えないと思うけど貼っておく。
以下は簡単なコードの例です(完全な実装ではありませんので注意してください):
<?php
/**
* Plugin Name: Auto Tag Generator using ChatGPT
* Description: Generates tags for posts using ChatGPT's morphological analysis.
*/
// Add action hook for post saving
add_action('save_post', 'auto_generate_tags');
function auto_generate_tags($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return;
// Get the post title
$post_title = get_the_title($post_id);
// Fetch tags using OpenAI API
$tags = fetch_tags_from_openai($post_title);
// Set the tags for the post
wp_set_post_tags($post_id, $tags, false);
}
function fetch_tags_from_openai($title) {
$api_url = "YOUR_OPENAI_API_ENDPOINT";
$api_key = "YOUR_OPENAI_API_KEY";
// Use the API to analyze the title
$response = wp_remote_post($api_url, array(
'headers' => array(
'Authorization' => 'Bearer ' . $api_key,
'Content-Type' => 'application/json'
),
'body' => json_encode(array(
'prompt' => 'Extract keywords from: "' . $title . '"',
'max_tokens' => 50
))
));
if (is_wp_error($response)) {
return array();
}
$body = wp_remote_retrieve_body($response);
$data = json_decode($body, true);
// Extract tags from the API response
// NOTE: This is a simple example and may need further refinement
$tags = explode(',', $data['choices'][0]['text']);
return $tags;
}
?>
コメントを残す