0

In a WordPress post, these multiple values exist for a custom metadata with the key "client"

client=>Andy
client=>Johny
client=>April

I want to add a new metadata only if its value does not exist,

Result wanted: client=>Andy will not be added because it already exists.

client=>Susan will be added because it does not exist The post will now have these metadata values

client=>Andy
client=>Johny
client=>April
client=>Susan
  • And what code do you use to add these custom fields? – Krzysiek Dróżdż May 27 '18 at 21:36
  • I have used Toolset plugin to create the custom field and then I used add_post_meta( $post_id, 'wpcf-client', $value ); to add values. Problem is it will create duplicates eventhough the existing value exists. – Calvin May 27 '18 at 21:49
  • It will, because add_meta_value does exactly what it says - it adds meta value - there are no checks if the value is unique. You’ll have to do them by yourself. – Krzysiek Dróżdż May 27 '18 at 21:50
  • And that is why i am asking about how to check the duplicates and add only if it is unique. I have tried several methods and it failed me. – Calvin May 27 '18 at 21:52
  • give me a moment ;) – Krzysiek Dróżdż May 27 '18 at 21:53
0

OK, so you have some code that uses add_post_meta and you want to make it add only unique values.

The problem in here is that add_post_meta does exactly what it's name is saying - it adds a post meta value. There is 4th arg for that function that's called unique, but it work based on key and not value.

All of that means that you have to do the checking by yourself... So you'll have to get all meta values using get_post_meta for that key and check if there already exists a meta with given value...

So how can that look like?

Somewhere in your code is a line looking like this:

add_post_meta( $post_id, $meta_key, $meta_value );

Just change it to this:

$existing_pms = get_post_meta( $post_id, $meta_key );
if ( ! in_array( $meta_value, $existing_pms ) ) {
    add_post_meta( $post_id, $meta_key, $meta_value );
}
  • Thanks. It worked. Previously i used $existing_pms = get_post_meta( $post_id, $meta_key,true ); and it did not work – Calvin May 28 '18 at 1:23

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.