I've a button, where the user create a post after click it. I want to notify him just after 10 min. I don't know the best way to do this with PHP. I know how to send the email, what I don't know is how to schedule this email for a specific time after the action. Has someone an idea?
1 Answer
There's wp_schedule_single_event:
$in_ten_minutes = time() + 10 * 60;
$post_id = get_the_ID();
wp_schedule_single_event( $in_ten_minutes, 'notify_post_event', array( $post_id ) );
or similar - I've no idea if it's just the post ID you need, or whether get_the_ID() is the right way to find it when you're handling this action. Depending on where the button is and how you want to handle the button press (AJAX? POST back to the page?) this may need to go in an AJAX handler somewhere, and have the post ID and any other values passed in.
And you'll need a handler function too, e.g.
function notify_post_event_handler( $post_id ) {
$the_post = get_post( $post_id );
$author_email = get_the_author_meta( 'user_email', $the_post-post_author );
wp_mail( $author_email,
'Here is your ten minute reminder',
'Post: ' . get_post_permalink( $post_id ) );
}
add_action( 'notify_post_event', 'notify_post_event_handler', 10, 1 );
and this will be triggered after ten minutes by the wp_cron processing, so you'll need to make sure you have something set up to regularly trigger wp_cron jobs if you don't have enough constant volume of visitors to trigger it automatically after ten minutes.
-
Thanks, sorry if I didn't see in the documentation before, I didn't know about this function. It is really working outside the ajax function. I understand about pass the variable. But I made a very simple function to be executed as this event (create a post). It works outside the Ajax function, but when I call via ajax, it doesn't work. Maybe it is because of the hook? Because this same function to create the post works inside the ajax call, but without the wp_schedule_single_event() Jul 4, 2020 at 15:07