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?
$_POST
is this intentional? My understanding is that's invalid PHP, and$_POST[post_ID];
should be$_POST['post_ID'];
. I also see it's readingdatum
in the AJAX handler, butdatum
is nowhere to be found in your AJAX code. Theadd_post_meta
fortest3
will never run because there's awp_die
just before it. From what I can tell, your PHP error log should be full of warnings and errors from that code. It's also not returning a response so there's no way to get info directly from the AJAX callfz.post_ID
has the expected value? Note that checking if the post meta is present afterwards is an integration test and you can't draw any conclusions beyond wether it worked or didn't work which isn't fine grained enough to answer itupdate_post_meta
should suffice and would be more reliable, but there is nothing wrong with your usage of those functions, the problem is elsewhere, it's more likely the variables being passed into the function don't have the values you think they do. Right now there's no evidence the AJAX endpoint is being called correctly,fz.ajax_url
may not have a valid value, there's no response to check, and no way to test for success or failure from JS