Could we help you? Please click the banners. We are young and desperately need the money
WordPress provides developers with a powerful set of hooks and actions to interact with various events that occur within the system. These events range from post creation to deletion and even changes in permalinks. As a developer, being able to respond to these events can enhance the functionality and user experience of your WordPress site. In this tutorial, we'll explore how to create alerts for three important post actions: creation, deletion, and permalink changes.
<?php
function post_permalink_change_alert($post_id, $post_after, $post_before) {
if (in_array($post_after->post_type, ['revision', 'attachment', 'nav_menu_item', 'wp_template', 'wp_template_part', 'acf-field', 'acf-field-group'])) {
return;
}
$old_permalink = get_permalink($post_before);
$new_permalink = get_permalink($post_after);
if ($old_permalink === $new_permalink) {
return;
}
error_log("Post {$post_id} \"{$post_after->post_title}\" permalink changed from \"{$old_permalink}\" to \"{$new_permalink}\"");
}
add_action('post_updated', 'post_permalink_change_alert', 10, 3);
?>
<?php
function post_created_alert($post_id, $post, $update){
if ($update) {
return;
}
if (in_array($post->post_type, ['revision', 'attachment', 'nav_menu_item', 'wp_template', 'wp_template_part', 'acf-field', 'acf-field-group'])) {
return;
}
error_log("Post {$post_id} \"{$post->post_title}\" created");
}
add_action('wp_insert_post', 'post_created_alert', 10, 3);
?>
<?php
function post_deleted_alert($post_id, $post){
if (in_array($post->post_type, ['revision', 'attachment', 'nav_menu_item', 'wp_template', 'wp_template_part', 'acf-field', 'acf-field-group'])) {
return;
}
error_log("Post {$post_id} \"{$post->post_title}\" deleted");
}
add_action('before_delete_post', 'post_deleted_alert', 10, 2);
?>
Developers are encouraged to customize the alert functionality to suit their needs. Instead of logging messages to the error log, you might want to send emails, display notifications within the WordPress dashboard, or integrate with third-party services for real-time alerts.
For example, you could modify the functions to send email alerts using WordPress's built-in wp_mail function:
<?php
function post_permalink_change_alert($post_id, $post_after, $post_before) {
// ...
// Instead of logging, send an email
$subject = 'Post Permalink Change Alert';
$message = "Post {$post_id} \"{$post_after->post_title}\" permalink changed from \"{$old_permalink}\" to \"{$new_permalink}\"";
wp_mail('admin@example.com', $subject, $message);
}
// Similar modifications for other alert functions
?>