The update_option()
function has a filter for that:
$value = apply_filters( "pre_update_option_{$option}", $new_value, $old_value );
Immediately after that filter, there’s another filter that you do not want to use.
$value = apply_filters( 'pre_update_option', $value, $option, $old_value );
(If you would use that, you will have to check the option name inside the callback, which adds unnecessary overhead.
What you need to do then, to react on a specific option changing contents by sending a mail via wp_mail()
, is to attach a callback to that filter. Read the @TODO
and fill in the missing bits:
<?php
/** Plugin Name: (#16621) Send mail after Option Value changed */
add_action( 'plugins_loaded', '166221reactMail' );
function 166221reactMail()
{
// @TODO Add you option names (valid triggers) here:
$valid = [
'your',
'option',
'names',
'here',
];
// Attach each filter: Precise targetting option names
foreach ( $valid as $name )
{
add_filter( "pre_update_option_{$name}", function( $new, $old )
{
# @TODO Adjust check/validity of mail trigger here
if ( $new !== $old )
{
# @TODO uncomment the following line - see note below
// add_filter( 'wp_mail_from', '166221reactMailFrom' );
# @TODO Adjust values for wp_mail()
wp_mail(
'[email protected]',
sprintf( 'Change notification from %s', get_option( 'blogname' ) ),
sprintf( 'Value changed from %s to %s', $old, $new )
);
}
return $new;
}
}
}
To make it easier to add creating highly specific mail inbox rules easier, you might want to add the following as well:
// @TODO Change "from" Name to make creating inbox rules easier
function 166221reactMailFrom( $from )
{
remove_filter( current_filter(), __FUNCTION__ );
return "[email protected]";
}
Edit
Just realized that I wrote an answer on the option filters, which doesn’t make any sense on post meta filters. You will have to exchange the filter names with those from update_metadata()
, which is triggered by the following from update_post_meta()
where the $meta_type
is post
. There are two filters or actions to use:
do_action( "update_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
or, if you know that you use a post
posttype:
do_action( 'update_postmeta', $meta_id, $object_id, $meta_key, $meta_value );
and if you want to trigger after the value has updated:
do_action( "updated_{$meta_type}_meta", $meta_id, $object_id, $meta_key, $_meta_value );
and specifically for the post
post type:
do_action( 'updated_postmeta', $meta_id, $object_id, $meta_key, $meta_value );