利用chatgpt在wordpress发布文章的时候根据标题提取关键词

以下是一个简单的插件示例,您可以将其保存为一个名为 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" =&gt; "system", "content" =&gt; "你是一个关键词提取器。从文章标题中提取3个核心SEO关键词,用逗号分隔
。"],
["role" =&gt; "user", "content" =&gt; "请从这个标题中提取关键词:{$title}"]
];$post_data = array(
    'model' =&gt; 'gpt-3.5-turbo',
    'messages' =&gt; $messages,
    'max_tokens' =&gt; 50,
    'temperature' =&gt; 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);
?>

给TA打赏
共{{data.count}}人
人已打赏
WP笔记

wordpress自动保存远程图片代码

2023-3-23 8:51:41

WP笔记

无需插件实现多个wordpress文章同步发布

2023-5-12 12:14:38

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索