讓 WordPress 外掛程式在特定事件後工作(例如,當建立草稿貼文時)
P粉265724930
P粉265724930 2024-01-10 18:11:14
0
1
529

我創建了一個 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粉265724930
P粉265724930

全部回覆(1)
P粉613735289

假設您已經熟悉如何在 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/

#下次,如果你想讓更多人願意閱讀並幫助你,請嘗試縮短程式碼並註解它

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板