The short answer: you can't.
The code is fine, but there is a flaw in logic. wp_head
action is set too late. Headers are already sent, therefore wp_head
will never fire! This code below, will prove two points. First: save_post
will fire on both, admin pages, and on front end, as well. Second: it's easy to prevent an infinite loop in callback function.
In functions.php
:
function saveCustomField($post_id) {
// to prevent an infinite loop
remove_action('save_post', 'saveCustomField', 10);
// to prove that function was called
error_log('I am here to add action');
add_action('wp_head', 'add_meta_tag');
}
add_action('save_post', 'saveCustomField');
function add_meta_tag(){
error_log('TEST');
//echo "TEST";
}
In my page template ( front end ):
wp_update_post(array('ID' => 79, 'post_title' => 'My Current Test',));
In error_log:
[19-Oct-2017 02:57:08 UTC] I am here to add action
My post's title had been updated, save_post
was fired, and wp_head
wasn't.
save_post
is called only in the admin pages and not on public side thensaveCustomField
is never called with this code. what do you want to display on public side ?save_post
is fired only on admin side. That's a myth! @JackJohansson: there is no chance of getting stuck in an infinite loop, if done correctly, by removing your action within the callback function.