Make a WordPress plugin work after a specific event (e.g. when a draft post is created)
P粉265724930
P粉265724930 2024-01-10 18:11:14
0
1
424

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

 

ChatGPT Dashboard

API Key
'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粉265724930
P粉265724930

reply all (1)
P粉613735289

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/

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

    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!