1

I have a custom post type (created with cmb2) which always contains a number (can be zero as well).

Some times i need to increase it by one with php, so i do this:

$value = (int) get_post_meta($post->ID,'myfieldkey',true); $value++; update_post_meta($post->ID,'myfieldkey', $value);

i guess i can make it a little shorter by doing this:

$value = (int) get_post_meta($post->ID,'myfieldkey',true); update_post_meta($post->ID,'myfieldkey', ++$value);

But still it seems to me like a very long code for this simple need.

My question is: Is there a shorter more efficient way to the same thing? (i am doing the same thing to multiple fields at the same time sometimes so it will really help me decrease the amount of code i'm using.

1 Answer 1

3

Enter WP_Post and the "magic" getter - did you know...

$value = get_post_meta( $post->ID, 'custom_field', true );

...is the same as

$value = $post->custom_field;

So you can shorten your code to:

update_post_meta( $post->ID, 'custom_field', $post->custom_field + 1 );

Note you cannot do $post->custom_field++ - since the property doesn't actually exist, it can't be modified. Read more about overloading in PHP.

1
  • Amazing! that's exactly the kind of solution i was looking for! Thank you very much!
    – Ben
    Nov 28, 2016 at 10:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.