Home  >  Q&A  >  body text

Make a WordPress plugin work after a specific event (e.g. when a draft post is created)

I created a WordPress plugin (with the help of ChatGPT) that rewrites post titles in drafts to meet my desired criteria of between 36 and 38 characters in length. Currently this is accomplished by clicking the Autofill button, which then lets ChatGPT rewrite the current draft title, then checks the reply to see its length, and if it doesn't meet the 36-38 character limit, the process is repeated until complete. Then change the title and publish the post.

This is working fine, however, I am trying to make it more automated so instead of having to log into WordPress and click a button to start the rewrite process, I would like it to happen as soon as I save a new draft post and the process then starts automatically. No matter what I try I can't do this, does anyone know how I can achieve this? Below is the code that works when I press the button manually

<?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');

Thanks in advance for any help/advice

I tried creating a hook and a cron job but my limited php knowledge was not able to achieve this

P粉265724930P粉265724930304 days ago496

reply all(1)I'll reply

  • P粉613735289

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

    Assuming you are already familiar with how to properly use and implement hooks in WordPress, I recommend using the hook "save_post". This is what I did:

    // 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') {
           
        }
    }

    refer to: https://developer.wordpress.org/reference/hooks/save_post/< /p>

    Next time, if you want more people to be willing to read and help you, try shortening the code and commenting it

    reply
    0
  • Cancelreply