I have a problem with the update_post_meta
function.
I have a user submitted value, which I pass via $_POST
and then saving to post meta.
All is working fine, but when the value is '0'
the post meta is not updated.
My code:
$id = absint($_POST['ex_id']);
$key = (string) $_POST['id'];
$value = (string) $_POST['value'];
echo update_post_meta($id, 'wpptabs_' . $key, $value);
Does anyone have any idea what might be wrong?
update_post_meta()
callsupdate_metadata
which begins with this line:I wrote a simple test (with a lot of cut & paste) to see how string values of 0 are evaluated (instead of looking it up in the PHP manual):
The result was:
So, to add a value of 0 you could change it to the string ‘0x0’ and cast it to integer when retrieving it. 0x0 is binary (I think) for 0.
PHP treats
0
as equivalent tofalse
for comparisons. Because theupdate_post_meta
function checks for a value before saving, it’s exiting because0 == false
.You could do something like this before saving the post meta, it’s a bit hacky but it would work:
Then when you’re retrieving your values later, you just do the opposite:
The issue is to do with this part of
update_metadata()
function withinmeta.php
thatupdate_post_meta()
callsAs the return value is
0
then the if statement correctly treats it as false, albeit0
has been saved to the database.This only happens when it updates. If a new post meta is added with a value of
0
then it returns the line id as expected.