I want to send email if a postmeta of a post is changed to the expected value.So previously i was doing loop to check the post meta in each post. In here am running the loop in admin_init
hook. But this slow down the site, so i’m thinking to do this on save post only. SO the edited post may have the meta value am expecting then i’ll send the mail.
Previous
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
if(get_post_meta($the_query->post->ID,'custom_post_meta',true)=='ok'){
//mail() function goes here
}
}
}
wp_reset_postdata();
This is unwanted because only certain post may be edited. Blindly checking post meta with a loop every time is waste.
So i thought to use on save_post
on save we’ll check whether the post meta is changed to the expected value then we’ll do the mail.like below
function testing($post_id){
if(get_post_meta($the_query->post->ID,'send_mail',true)=='ok'){
//mail() function goes here
}
//only for edited post alone i'm checking here
}
add_action('save_post','testing');
There are another two scenario where the post meta may be changed which are bulk edit and quick edit
For quick edit i found this
function check(){
var_dump($_REQUEST);//can able to get the post id, i can do the rest
}
add_action('check_ajax_referer','check');
But for bulk edit i don’t have any clue. I tried searching, In this answer i found that $_REQUEST
may contain action
and postid
. So i thought for bulk edit there might be an action in $_REQUEST['action']
but i couldn’t find when i try like this
function another_check(){
var_dump($REQUEST['action']);
}
add_action('admin_init','another_check');
I found this check_admin_referer
too but i couldn’t able to figure out as it does not print when i var dump. Will this(check_admin_referer
) work or suit on this? Is there any other easy way to get the edited post ids?
How can i get the List of post id on bulk edit? From then i can able to do the check and send mail accordingly
If your problem is:
Why do yous ask for:
This is a typical x/y problem: when you have a problem, ask how to solve that problem, instead of asking ways to apply what you think is the solution…
Going in the details, you want to perform an action when a meta field is updated? Why don’t just look at.. the moment it is updated?
Everytime a post meta is updated, WordPress call the hook
'updated_postmeta'
like sodo_action("updated_{$type}_meta", $meta_id, $object_id, $meta_key, $meta_value);
where
$type
is'post'
.As you can see, you have enough informations to do anything you want.
Let’s assume you want to send a mail to the post author everytime the meta ‘send_mail’ is set to ‘ok’:
Note that this code runs only when a meta is updated, and not when is added.
To run same code when the meta is also added, just add another action:
Both hooks work in identical way, passing identical arguments, so no problem on using same function for both.