post meta – add_post_meta not working within AJAX function
I’m passing some data through AJAX to a function in my functions.php, and am trying to save that as metadata to post ‘101’ with a key name “test1”. My PHP function is:
function fztest(){
$datum = $_POST['datum'];
$post_ID = $_POST['post_ID'];
add_post_meta($post_ID, 'test1', $datum);
// And since $datum and $post_ID are correctly returning the values I want, but the meta is not saving,
// I've tried troubleshooting by putting some manual operations in various places below:
add_post_meta(101, 'test2', 'foobar');
wp_die();
add_post_meta(101, 'test3', 'foobar');
}
add_action('wp_ajax_foobar', 'fztest');
add_action('wp_ajax_nopriv_foobar', 'fztest');
add_post_meta(101, 'test4', 'foobar');
But when I try to return get_post_meta(101, ‘test1’), for example – only ‘test4’ above works – it just returns an empty string for test1, test2 and test3.
My JS is:
$.ajax({
url: fz.ajax_url,
type: "POST",
data: {
action: "foobar",
datum: "foobar",
post_ID: fz.post_ID,
},
success: function(response){
}
})
… and that is correctly passing the values through to the PHP function, and logging a response when I have tried one.
I can’t see why add_post_meta would not work in the PHP function? There’s a similar question here where the solution indicates it clearly should and CAN work. How do I update_post_meta() or add_post_meta() with an AJAX call. And their code looks the same as mine as far as I can see.
Can anyone see what I’m doing wrong?
Leave an answer