WordPress 接入 Chat GPT / OpenAI API

完成以上准备功能,就可以编辑你的 WordPress 当前主题的 functions.php 文件,将以下代码添加到合适的位置即可实现 OpenAI 自动生成 WordPress 标签描述内容,但是需要注意的是 OpenAI 生成内容需要时间,所以可能需要稍等片刻才能在标签中看到自动生成的描述内容,其次则是只会对新增的标签自动生成,不会影响已经存在的标签。

//WordPress 新增文章标签动作
add_action('created_post_tag', 'fanly_basic_created_post_tag', 10, 3);
function fanly_basic_created_post_tag($term_id, $tt_id, $args) {
	wp_remote_post( admin_url( 'admin-ajax.php' ), [
		'blocking'	=> false,
		'timeout'	=> 1,
		'body'		=>[
			'action'	=> 'fanly_basic_post_tag_description',
			'term_id'	=> $term_id,
			'name'		=> $args['name'] ?? null
		]
	]);
}
//WordPress 标签描述自动生成
add_action('wp_ajax_fanly_basic_post_tag_description', 'fanly_basic_post_tag_description');
add_action('wp_ajax_nopriv_fanly_basic_post_tag_description', 'fanly_basic_post_tag_description');
function fanly_basic_post_tag_description() {
	$term_id = $_POST['term_id'];
	$name = $_POST['name'];
	if($name){
		$prompt = $name . '是什么 回答至少 300 字,且必须是简体中文。';//标签名称+要求
		$token = 'sk-添加你自己的 key';//secret key
		$api = 'https://api.openai.com';//接口地址,或者是反向代理的镜像地址
		$res = wp_remote_post("$api/v1/chat/completions", [
			'headers' => ['Content-Type'=>'application/json','Authorization'=>"Bearer $token"],
			'timeout' => 300,
			'body' => json_encode([
				'model' => 'gpt-3.5-turbo',//gpt-3.5-turbo gpt-4
				'messages' => [[
					'role' => 'user',
					'content' => $prompt
				]],
				'max_tokens' => 3000
			])
		]);
		if(!is_wp_error($res)){
			$body = json_decode($res['body'], true);
			$content = $body['choices'][0]['message']['content'] ?? null;
			$description = trim($content);
			if($description){
				wp_update_term($term_id, 'post_tag', ['description'=>$description]);
			}
		}
	}
}

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注