I am using the hook publish_post
to run my code where I need the post meta of the just published post. But the post meta value I am looking for is somehow not available at this point of execution. On checking the wp_postmeta
table, I found that my meta key value hasn’t been created yet. Also, I want this to work for a post published for the first time. Is there any other hook that can give me access to it?
function push_notification($post_id)
{
$ref_ids = get_post_meta($post_id,'ref_id');
if($ref_ids)
{
//my code goes here
}
}
add_action('publish_post','push_notification');
3 Answers
Solved it! Used save_post
to run push_notification()
as well as to run the function save_post_meta()
that saves my post meta. The problem occurred coz push_notification()
gets fired before save_post_meta()
due to which the meta wasn’t being saved and therefore it remained inaccessible. Just changed priorities of the functions to make it work like so :
function push_notification($post_id)
{
$ref_ids = get_post_meta($post_id,'ref_id');
if($ref_ids)
{
//my code goes here
}
}
add_action('save_post','push_notification',11,1);
function save_post_meta($post_id,$post)
{
//check for nonces and current user capabilities
$ref_id = sanitize_html_class($_POST['ref_id']);
update_post_meta($post_id,'ref_id',$ref_id);
}
add_action('save_post','save_post_meta',10,2);
function no_notification()
{
remove_action('save_post','push_notification',11,1);
}
add_action('publish_to_publish','no_notification');
The last function no_notification()
makes sure that push_notification()
gets fired only when a post is first created and not for updates.