update_post_meta adds one to value
-
In the code below, I pull the page view counter from postmeta and increment it by one.
When I update via update_post_meta, the counter value that goes into the database is incremented mysteriously by 1 again. So, if the counter was at 3, after the update it will be set to 5.
If, however, I update the record directly via mysql_query, the counter value in the database is set to what I calculated, that is 1+the old counter, not 2+the old counter.
I would prefer to use update_post_meta. But why is it doing this?
Here is my code with my debugging statements. You can see the two different ways I try to update the database down in the last few lines of code. One way is commented out, because I was testing.function setPostViews($postID) { $count_key = 'Views'; $count=0; $count = get_post_meta($postID, $count_key, true); var_dump($count); echo "count " . $count . "<br>"; if($count==''){ $count = 1; delete_post_meta($postID, $count_key); add_post_meta($postID, $count_key, '1'); }else{ $count++; // update_post_meta($postID, $count_key, $count); $query="update hoparticlespostmeta set meta_value='".$count."' where meta_key='Views' and post_id=".$postID; mysql_query($query); } }
-
I tested your code exactly as you posted it using update_post_meta() and commenting out the 2 query lines and it works as expected.
Every time I refreshed the page the count updated by 1
I added
setPostViews( get_the_ID() );
inside the loop in single.phpThank you. That is good.
Unfortunately, I am still getting the same result on my side. To further investigate, I put an echo statement in the update_post_meta function in wp-includes/posts.php.
I echoed the meta_value argument and it gave me the bad value. That is: count had a value of 10, but the value that update_post_meta echoed was 11. So the problem occurs early on, between my php and wordpress’s php, but how? And not on your site… Seriously, I am witnessing the impossible!
Grr. I have the workaround to use, and I generalized my query by using wpdb instead of identifying my table expressly. But I want the real code to work…Oh well, add it to my list of website mysteries.
add_post_meta() ends up calling update_meta_data(), which has several hooks. I suspect some plugin is conflicting with your code via one of these hooks. You might try using a more unusual key than a generic “Views”, always good practice btw.
Thanks everyone! I am finding a number of impossible issues with this wordpress install.
- The topic ‘update_post_meta adds one to value’ is closed to new replies.