wordpressadditionpost-meta

I want to add a new value in the post meta without deleting the old value


I have post meta "metaname" with value "thatsme" and I want to add a new value "thatsyou" in the post meta "metaname" without deleting the old value "thatsme"

so the result will be:

how to do it in wordpress?


Solution

  • You can do this simply using add_post_meta as normal.

    The 4th (optional) parameter is a boolean to indicate whether the meta key should be unique or not:

    You already have a key set up, presumably using code like this:

    add_post_meta( $post_id, 'metaname', 'thatsme');
    

    To add another value, you just to the same again - I've added false for the unique parameter here to highlight it, but it is the default value so there is no need

    add_post_meta( $post_id, 'metaname', 'thatsyou');
    

    Then to retrieve all the values of the meta-key, you can do the following:

    $my_meta_keys = get_post_meta( $post_id, 'metaname', false );   // get all values for this key
    if ( ! empty( $my_meta_keys ) ) {
        // loop through all values 
        foreach( $my_meta_keys as $value)
            echo $value;  // or whatever you want to do with it
    }
    

    References: