1

how do you create a 1+1 php counter inside the update_post_meta?

this is the code i have so far:

$count = 1;
update_post_meta($bid_id, 'draftnumber', $count++);

but the counter is not moving, so i tried another one:

$counting = $counting + 1;
update_post_meta($bid_id, 'draftnumber', $counting);

but it's not working, am i not allowed to use $count++ inside the update_post_meta?

thankyou

2
  • Would you be able to post the rest of the function? Bit hard to tell whats going on with just this little snippet. – ngearing May 26 '16 at 2:26
  • $count++; right after $count = 1; so $count = 1; $count++; then update. It has to do with $bid_id I assume with this one. – Ismail May 26 '16 at 2:36
6

If you're trying to update the number stored in the meta table, you need to load that value and increment it.

$count = get_post_meta( $bid_id, 'draftnumber', true );
if ( ! $count ) {
    $count = 0;  // if the meta value isn't set, use 0 as a default
                 // We'll be incrementing this right away so it'll be 1
}
$count++;
update_post_meta( $bid_id, 'draftnumber', $count );

References

3
  • 1
    While this works, one problem is that with the current logic, you start at 1 and add 1, so the first count would be 2. You should start at 0. – Calara Ionut Mar 30 '19 at 12:54
  • Good catch, @CalaraIonut; I've corrected it. – Pat J Apr 1 '19 at 13:57
  • 1
    Just to elaborate (for the benefit of the original poster, and whoever else might come along), let me clarify a bit how WordPress works. With each incoming request, the WordPress code starts up, generates the page, then goes away. If you want anything to last between requests, it should go in the database. – Loren Rosen Apr 1 '19 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy