0

I want to update the wp_postmeta table in the database based on 2 keys, is there a way to do that using any of the wordpress default functions. This is my DB query which is working fine:

$sql = "UPDATE wp_postmeta SET meta_value = meta_value + 1 WHERE post_id = 167788 AND meta_key = \"tie_views\"";

1 Answer 1

0

Yes, there is.

These are some WP functions to get, add and update post meta values:

get_post_meta()

add_post_meta()

update_post_meta()

Your code could be:

$meta_value = (int) get_post_meta( $post->ID, 'meta_key', true );
update_post_meta( $post->ID, 'meta_key', $meta_value + 1 );
3
  • Thanks a lot. I have tested it, it is working fine. Please be kind enough to tell me what does the first (int) means
    – H_alt
    Commented Aug 18, 2020 at 10:31
  • 1
    @H_alt That's because the function returns a single string value, if you want to use it as a number you should cast the value to proper type.
    – Had1z
    Commented Aug 18, 2020 at 10:41
  • thanks for the explanation, I forgot about the type casting, you are right.
    – H_alt
    Commented Aug 18, 2020 at 10:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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