首页  >  问答  >  正文

让 WordPress 插件在特定事件后工作(例如,当创建草稿帖子时)

我创建了一个 WordPress 插件(在 ChatGPT 的帮助下),它可以重写草稿中的帖子标题,以满足我需要的长度在 36 到 38 个字符之间的标准。目前这是通过单击“自动填充”按钮来实现的,然后让 ChatGPT 重写当前草稿标题,然后检查回复以查看其长度,如果不符合 36-38 个字符的限制,则过程为重复直到完成。然后更改标题并发布帖子。

这工作正常,但是,我试图使其更加自动化,因此不必登录 WordPress 并单击按钮来启动重写过程,只要保存新的草稿帖子,我就希望它,该过程然后自动启动。无论我尝试过什么,我都无法做到这一点,有谁知道我如何实现这一目标?下面是我手动按下按钮时有效的代码

<?php
/*
Plugin Name: ChatGPT Dashboard
*/

// Add a custom menu item to the WordPress dashboard
function chatgpt_dashboard_menu() {
  add_menu_page(
    'ChatGPT Dashboard',
    'ChatGPT',
    'manage_options',
    'chatgpt-dashboard',
    'chatgpt_dashboard_page',
    'dashicons-format-chat', // You can change the icon here
    20
  );
}
add_action('admin_menu', 'chatgpt_dashboard_menu');

// Enqueue jQuery UI library
function chatgpt_enqueue_scripts() {
  wp_enqueue_script('jquery-ui-core');
  wp_enqueue_script('jquery-ui-draggable');
}
add_action('admin_enqueue_scripts', 'chatgpt_enqueue_scripts');

// Register plugin settings
function chatgpt_register_settings() {
  register_setting('chatgpt_options', 'chatgpt_api_key');
}
add_action('admin_init', 'chatgpt_register_settings');

// Callback function to display the ChatGPT dashboard page
function chatgpt_dashboard_page() {
  ?>
  <div class="wrap">
    <h1>ChatGPT Dashboard</h1>

    <!-- API Key settings form -->
    <form method="post" action="options.php">
      <?php settings_fields('chatgpt_options'); ?>
      <?php do_settings_sections('chatgpt_options'); ?>
      <table class="form-table">
        <tr valign="top">
          <th scope="row">API Key</th>
          <td><input type="text" name="chatgpt_api_key" value="<?php echo esc_attr(get_option('chatgpt_api_key')); ?>" /></td>
        </tr>
      </table>
      <?php submit_button(); ?>
    </form>

    <!-- Chat interface -->
    <div id="chat-container">
      <div id="chat-log"></div>
      <input type="text" id="user-input" placeholder="Type your message..." />
      <button id="submit-button">Send</button>
      <button id="autofill-button">Autofill</button>
    </div>
  </div>

  <script>
    (function ($) {
      $(document).ready(function () {
        // Function to handle user input and generate ChatGPT responses
        function handleUserInput() {
          var userInput = $('#user-input').val();

          // Get the API key from the WordPress options database
          var apiKey = '<?php echo get_option("chatgpt_api_key"); ?>';

          // Make sure the API key is provided
          if (!apiKey) {
            alert('Please enter an API key in the ChatGPT dashboard settings.');
            return;
          }

          // Make an API call to ChatGPT to get a response
          function callChatGPT() {
            $.ajax({
              url: 'https://api.openai.com/v1/chat/completions',
              type: 'POST',
              beforeSend: function (xhr) {
                xhr.setRequestHeader('Authorization', 'Bearer ' + apiKey);
                xhr.setRequestHeader('Content-Type', 'application/json');
              },
              data: JSON.stringify({
                model: 'gpt-3.5-turbo',
                messages: [
                  { role: 'system', content: 'You are a user' },
                  { role: 'user', content: userInput },
                ],
              }),
              success: function (response) {
                var chatLog = $('#chat-log');

                if (!response.choices || !response.choices.length) {
                  chatLog.append('<p><strong>Error:</strong> No response received</p>');
                  return;
                }

                var botResponse = response.choices[0].message.content;

                // Check if botResponse is an array
                if (Array.isArray(botResponse)) {
                  botResponse = botResponse.map(msg => msg.content).join('');
                }

                // Count the number of characters in the bot response
                var characterCount = botResponse.length;

                // Display the user input, bot response, and character count in the chat log
                chatLog.append('<p><strong>You:</strong> ' + userInput + '</p>');
                chatLog.append('<p><strong>Bot:</strong> ' + botResponse + '</p>');
                chatLog.append('<p><strong>Character count:</strong> ' + characterCount + '</p>');

                // Clear the user input field
                $('#user-input').val('');

                // Scroll to the bottom of the chat log
                chatLog.scrollTop(chatLog.prop('scrollHeight'));

                // Check if the character count is within the desired range (36, 37, or 38)
                if (characterCount >= 36 && characterCount <= 38) {
                  // Print the new title 5 times in a row
                  for (let i = 0; i < 5; i++) {
                    chatLog.append('<p><strong>New Title:</strong> ' + botResponse + '</p>');
                  }
                  
                 // Create a new post with the new title and set it as a draft
$.ajax({
  url: '<?php echo admin_url("admin-ajax.php"); ?>',
  type: 'POST',
  data: {
    action: 'create_draft_post',
    title: botResponse,
  },
  success: function (response) {
    console.log('Draft post updated:', response);
    chatLog.append('<p><strong>New Title:</strong> ' + botResponse + '</p>');
  },
  error: function (xhr, status, error) {
    console.error(error); // Log any errors to the browser console
  },
});

                  return; // Exit the function if the condition is met
                }

                // Repeat the question until the character count is within the desired range
                callChatGPT();
              },
              error: function (xhr, status, error) {
                var chatLog = $('#chat-log');
                chatLog.append('<p><strong>Error:</strong> ' + error + '</p>');
                console.error(error); // Log any errors to the browser console
              },
            });
          }

          callChatGPT(); // Initial call to ChatGPT
        }

        // Handle user input when the submit button is clicked
        $('#submit-button').on('click', function (e) {
          e.preventDefault();
          handleUserInput();
        });

        // Handle user input when the enter key is pressed
        $('#user-input').on('keydown', function (e) {
          if (e.keyCode === 13) {
            e.preventDefault();
            handleUserInput();
          }
        });
// Handle autofill button click
$('#autofill-button').on('click', function (e) {
  e.preventDefault();

  // Get the draft posts
  $.ajax({
    url: '<?php echo admin_url("admin-ajax.php"); ?>',
    type: 'POST',
    data: {
      action: 'get_draft_posts',
    },
    success: function (response) {
      if (response && response.length) {
        var draftTitle = response[0].post_title;
        var autofillText = 'Summarize "' + draftTitle + '" to 38 characters';
        $('#user-input').val(autofillText);
        
        // Automatically start the process of generating the response
        handleUserInput();
      }
    },
    error: function (xhr, status, error) {
      console.error(error); // Log any errors to the browser console
    },
  });
});
      });
    })(jQuery);
  </script>
  <?php
}

// AJAX handler to retrieve draft posts
function chatgpt_get_draft_posts() {
  $draftPosts = get_posts(array(
    'post_status' => 'draft',
    'numberposts' => 1,
  ));
  wp_send_json($draftPosts);
}
add_action('wp_ajax_get_draft_posts', 'chatgpt_get_draft_posts');
add_action('wp_ajax_nopriv_get_draft_posts', 'chatgpt_get_draft_posts');

// AJAX handler to update the existing draft post with the new title and publish it
function chatgpt_create_draft_post() {
  $title = $_POST['title'];

  $draftPosts = get_posts(array(
    'post_status' => 'draft',
    'numberposts' => 1,
  ));

  if (empty($draftPosts)) {
    wp_send_json_error('No draft post found.');
    return;
  }

  $draftPost = $draftPosts[0];
  $draftPostID = $draftPost->ID;

  // Update the title of the draft post
  wp_update_post(array(
    'ID'         => $draftPostID,
    'post_title' => $title,
    'post_status' => 'publish',
  ));

  wp_send_json_success($draftPostID);
}
add_action('wp_ajax_create_draft_post', 'chatgpt_create_draft_post');
add_action('wp_ajax_nopriv_create_draft_post', 'chatgpt_create_draft_post');

预先感谢您的任何帮助/建议

我尝试创建一个钩子和一个 cron 作业,但我有限的 php 知识无法实现这一点

P粉265724930P粉265724930307 天前507

全部回复(1)我来回复

  • P粉613735289

    P粉6137352892024-01-11 09:17:09

    假设您已经熟悉如何在 WordPress 中正确使用和实现钩子,我建议使用钩子“save_post”。 我就是这样做的:

    // Register the hook
    add_action('save_post', 'your_function');
    
    // Whatever function you need to be executed
    function your_function($post_id) {
        // Check if the post is a draft
        if (get_post_status($post_id) === 'draft') {
           
        }
    }

    参考: https://developer.wordpress.org/reference/hooks/save_post/< /p>

    下次,如果你想让更多人愿意阅读并帮助你,请尝试缩短代码并注释它

    回复
    0
  • 取消回复