1
0

hooks.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. namespace IROChatGPT {
  3. use HaoZiTeam\ChatGPT\V2 as ChatGPTV2;
  4. use WP_Post;
  5. define('MAX_MESSAGE_LENGTH', 4096);
  6. define("DEFAULT_INIT_PROMPT", "You are a excerpt generator. " .
  7. "You can summarize articles given their title and full text. " .
  8. "You should use the same language as the article for your excerpt. " .
  9. "You do not need to write in third person.");
  10. define('DEFAULT_ASK_PROMPT', "Please summarize articles provided before.");
  11. define('POST_METADATA_KEY', "ai_summon_excerpt");
  12. function is_not_in_excluded_ids($id_list_str, $post_id) {
  13. $id_list_str = str_replace(" ", "", $id_list_str);
  14. $id_list = explode(",", $id_list_str);
  15. $id_list = array_map('intval', $id_list);
  16. return !in_array($post_id, $id_list, true);
  17. }
  18. function apply_chatgpt_hook() {
  19. $exclude_ids = iro_opt('chatgpt_exclude_ids','');
  20. $exclude_ids_arr = explode(',',$exclude_ids);
  21. if (iro_opt('chatgpt_article_summarize')) {
  22. add_action('save_post_post', function (int $post_id, WP_Post $post, bool $update) use ($exclude_ids) {
  23. if (is_not_in_excluded_ids($exclude_ids, $post_id) && !has_excerpt($post_id)) {
  24. try {
  25. $excerpt = summon_article_excerpt($post);
  26. update_post_meta($post_id, POST_METADATA_KEY, $excerpt);
  27. } catch (\Throwable $th) {
  28. error_log('ChatGPT-excerpt-err:' . $th);
  29. }
  30. }
  31. }, 10, 3);
  32. add_filter('the_excerpt', function (string $post_excerpt) {
  33. global $post;
  34. if (has_excerpt($post)) {
  35. return $post_excerpt;
  36. } else {
  37. $ai_excerpt = get_post_meta($post->ID, POST_METADATA_KEY, true);
  38. return $ai_excerpt ? $ai_excerpt : $post_excerpt;
  39. }
  40. });
  41. }
  42. }
  43. function summon_article_excerpt(WP_Post $post) {
  44. $chatGPT_base_url = iro_opt('chatgpt_base_url');
  45. $chatGPT_access_token = iro_opt('chatgpt_access_token');
  46. $chatGPT_prompt_init = iro_opt('chatgpt_init_prompt', DEFAULT_INIT_PROMPT);
  47. $chatGPT_prompt_ask = iro_opt('chatgpt_ask_prompt', DEFAULT_ASK_PROMPT);
  48. $chatGPT = new ChatGPTV2($chatGPT_access_token, $chatGPT_base_url);
  49. $chatGPT->addMessage($chatGPT_prompt_init, 'system');
  50. $chatGPT->addMessage("文章标题:" . $post->post_title, 'user');
  51. $content = $post->post_content;
  52. $content = substr(wp_strip_all_tags(apply_filters('the_content', $content)), 0, 4050);
  53. $chatGPT->addMessage("正文:" . $content, 'user');
  54. $answer = '';
  55. foreach ($chatGPT->ask($chatGPT_prompt_ask) as $item) {
  56. $answer .= $item['answer'];
  57. }
  58. return $answer;
  59. }
  60. }