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 );
}