以下是一个简单的插件示例,您可以将其保存为一个名为 auto_keyword_extraction.php
的文件,并将其上传到WordPress的 wp-content/plugins
目录中,然后在WordPress后台启用这个插件。将以下$openai_key = '123456'; 中的123456换成你的key
<?php /* Plugin Name: 关键词提取 Description: 使用OpenAI API从文章标题中提取关键词 Version: 1.0 Author: 787K.COM */ //原文地址:https://wpriji.com/m/202303337.html <!--?php /* Plugin Name: 关键词提取 Description: 使用OpenAI API从文章标题中提取关键词 Version: 1.0 Author: 787K.COM */ //原文地址:https://wpriji.com/m/202303337.html function extract_keyword_from_title($post_id) { // 检查文章是否已经有标签 $post_tags = wp_get_post_terms($post_id, 'post_tag'); if (!empty($post_tags)) { error_log('Post already has tags. Skipping keyword extraction.'); return; } $title = get_the_title($post_id); $openai_key = '123456'; $openai_url = 'https://api.openai.com/v1/chat/completions'; $headers = array( 'Content-Type: application/json', 'Authorization: Bearer ' . $openai_key, ); $messages = [ ["role" => "system", "content" => "你是一个关键词提取器。从文章标题中提取3个核心SEO关键词,用逗号分隔 。"], ["role" => "user", "content" => "请从这个标题中提取关键词:{$title}"] ];$post_data = array( 'model' => 'gpt-3.5-turbo', 'messages' => $messages, 'max_tokens' => 50, 'temperature' => 0.9, ); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $openai_url); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data)); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); $response = curl_exec($ch); curl_close($ch); $response_data = json_decode($response, true); error_log('API Response: ' . print_r($response_data, true)); if (isset($response_data['choices'][0]['message']['content'])) { $keywords = trim($response_data['choices'][0]['message']['content']); $keywords_array = array_map('trim', explode(",", $keywords)); $top_keywords = array_slice($keywords_array, 0, 3); // Select the top 3 keywords wp_set_object_terms($post_id, $top_keywords, 'post_tag', true); error_log('Extracted Keywords: ' . implode(', ', $top_keywords)); } else { error_log('Keyword extraction failed. No keyword found.'); } } add_action('publish_post', 'extract_keyword_from_title', 10, 1); ?>
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END