我已经创建了一个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知识还没有能够实现这一点
1条答案
按热度按时间exdqitrt1#
假设你已经熟悉如何在wordpress中正确使用和实现钩子,我建议使用钩子“保存_post”。我会这么做
字符串
参考:https://developer.wordpress.org/reference/hooks/save_post/
下一次,如果你想让更多的人愿意通读代码并帮助你的话,试着缩短代码并注解它