Question

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
Was it helpful?

Solution

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

OTHER TIPS

I know this post is a little outdated but just in case anyone comes across this, I've written a function that checks for any pre-existing metadata attached a given post.

/**
 * Check if post has pre-existing metadata.
 *
 * @see metadata_exists()
 *
 * @param int    $post_id  The post ID.
 * @param string $meta_key The meta key to look for.
 *
 * @return bool            True if key is found. False if not.
 */
function wpse304585_post_meta_exists( $post_id, $meta_key ) {
    if ( metadata_exists( 'post', $post_id, $meta_key ) ) {
        return true;
    }

    return false;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top