Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

Does anyone know of a plugin that is capable of merging the post meta from one post into another?

I'm working on re-releasing the Driftwood contact manager theme and I'm trying to find a way to solve the duplicate contact issue. Obviously this question could impact far more people than just myself. :)

share|improve this question
add comment

1 Answer

up vote 1 down vote accepted
/**
 * Merge metadata from one post to another.
 * 
 * @param int $from_ID Source post ID
 * @param int $to_ID Target post ID
 * @param bool $overwrite Whether to overwrite metadata if the key already exists
 * @return bool|array
 */  
function wpse_20231_merge_postmeta( $from_ID, $to_ID, $overwrite = true )
{
    // get ALL metadata for $from_ID
    if ( !$source_meta = get_metadata( 'post', $from_ID ) )
        return false;

    if ( !$existing_meta = get_metadata( 'post', $to_ID ) )
        $existing_meta = array();

    // loop over source meta and update, depending on if overwrite is true & existing meta exists
    foreach ( $source_meta as $key => $value ) {
        if ( $overwrite ? true : !isset( $existing_meta[ $key ] ) )
            update_post_meta( $to_ID, $key, maybe_unserialize( $value ) );
    }

    // return new meta data
    // using plus is like array merge, but from left to right - proceding duplicate keys are ignored
    return $overwrite ? $source_meta + $existing_meta : $existing_meta + $source_meta;
}
share|improve this answer
    
So if I am understanding you if I create a page template with two inputs, one for $from_ID and another for $to_ID would I just throw in a submit button (to itself?) or am I missing it entirely? –  mattrepublic Jun 17 '11 at 20:07
    
The code was a 'lead by example' sorta thing - how you implement it is up to you. So yeah, you could keep the function as-is, and just call it using data from a POST'ed form, if that's what you need. –  TheDeadMedic Jun 17 '11 at 20:19
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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